HTML 5 introduces many new exciting features, and it is very tempting for the web developer to start buiding pages taking advantage of this new syntax as soon as an early implementation shows up.
For those aiming at the masses, it may however be necessary to fill the HTML 5 implementation gaps of some browsers with custom javascript implementations.
Fair enough, says the web developer: thanks to Javascript extensibility mechanisms, it is easy to add new properties and methods to existing objects and even to create new javascript objects, but what about all these new javascript events ?
Well my friends, since DOM level 2 specification it is possible to create, initialize and dispatch custom javascript events.
Basically you can create a javascript event by calling the DOM document createEvent method:
var evt = document.createEvent("Event");
...
var mevt = document.createEvent("MouseEvent");
The createEvent argument defines the Event interface:
UIEvent: for DOMFocusIn, DOMFocusOut & DOMActivate eventsMouseEvent: for click, mousedown/up/over/move/outMutationEvent: for all DOMXX modification eventsHTMLEvent: for load, unload, abort, error, select, change, submit, reset, focus, blur, resize, scroll eventsEvent: Any other event
Note: You cannot generate a key event
Once you’ve instantiated an event of a specific type, you can specify its attributes using the corresponding initEvent method:
var evt = document.createEvent("Event");
evt.initEvent("myEvent",true,true);
...
var mevt = document.createEvent("MouseEvent");
mevt.initMouseEvent("click",true,true,...);
The first three parameters are common to all initEvents functions: the first argument specifies the event type, the second indicates if the event can bubble and the third if its default action can be prevented.
Once the event has been created and initialized, it can be dispatched to the document or to a specific node:
var evt = document.createEvent("Event");
evt.initEvent("myEvent",true,true);
document.dispatchEvent(evt);
...
or
...
var target = document.getElementById("myTarget");
target.dispatchEvent(evt);
Of course, you also need to specify an event handler if you actually want to catch this new event:
document.addEventListener("myEvent",myEventHandler,false);
...
or
...
var target = document.getElementById("myTarget");
target.addEventListener("myEvent",myEventHandler,false);