Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  111] [ 4]  / answers: 1 / hits: 32597  / 11 Years ago, mon, january 13, 2014, 12:00:00

As shown in the demo, dispatchEvent is not working as expected.


http://jsfiddle.net/DerekL/V8uEN/


Key part:


btn.dispatchEvent(
document.createEvent("MouseEvent")
.initMouseEvent("click", true, true, window, 0,
0, 0, 0, 0,
false, false, false, false,
0, null)
);

An alert should pop up after 1 second upon loaded, but it is not coming up and an error appears in the console:



Uncaught InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event provided is null.



I don't know where's the problem at since I found a demo almost with the exact same code, and it is working but not mine.


More From » dom-events

 Answers
43
btn.dispatchEvent(
document.createEvent(MouseEvent)
.initMouseEvent(click, true, true, window, 0,
0, 0, 0, 0,
false, false, false, false,
0, null)
);


Your problem is that initMouseEvent doesn't return anything. You can't combine all of that into one line. You need to break it up.



var mEvent = document.createEvent(MouseEvent);
mEvent.initMouseEvent(click, true, true, window, 0,
0, 0, 0, 0,
false, false, false, false,
0, null);

btn.dispatchEvent(mEvent);


This is how it's done in the demo you linked to.


[#73196] Sunday, January 12, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
kevonmoisesf questions
Sat, Jan 23, 21, 00:00, 3 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
;