As shown in the demo, dispatchEvent
is not working as expected.
/
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.
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.
Share Improve this question edited Apr 1, 2023 at 19:44 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Jan 13, 2014 at 20:17 Derek 朕會功夫Derek 朕會功夫 94.3k45 gold badges195 silver badges253 bronze badges 3- worked for me. using chrome here. – T McKeown Commented Jan 13, 2014 at 20:19
- @TMcKeown - That's weird, I'm using Chrome 32 on Windows but it's not working. – Derek 朕會功夫 Commented Jan 13, 2014 at 20:20
- sorry, it's not popping up automatically. – T McKeown Commented Jan 13, 2014 at 20:21
2 Answers
Reset to default 12btn.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.
This works:
var btn = document.querySelector("button");
btn.addEventListener("click", function () {
alert("Clicked.");
});
setTimeout(function () {
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);
}, 1000);