Here’s my code, it’s based off the example provided at MDN:
window.onload = function(){
var element = document.createElement('div');
var event = document.createEvent("HTMLEvents");
event.initEvent("myClick", true, false);
element.dispatchEvent(event);
document.addEventListener("myClick", function(){
alert("myClick event caught");
}, false);
}
When I run this, nothing happens, indicating something went wrong in the creation, sending or catching of the event. I would appreciate any help in understanding where I am going wrong here.
@Pablo Fernandez is right in his answer about the order, but another component is that your element needs to be in the DOM.
The reason is that you’re making the event a bubbling event, and attaching the handler to the
document. Well in order for the event to bubble up to thedocument, the element it’s bubbling from needs to be within thedocument.Example: http://jsfiddle.net/nhsN4/
If you had added the handler directly to the
elementyou created, then you could dispatch the event without it being in thedocument.Example: http://jsfiddle.net/nhsN4/1/