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.
var evt = document.createEvent("Event"); ... var mevt = document.createEvent("MouseEvent");
createEvent argument defines the Event interface:
UIEvent: for DOMFocusIn, DOMFocusOut & DOMActivate events,
MouseEvent: for click, mousedown/up/over/move/out,
MutationEvent: for all DOMXX modification events,
HTMLEvent: for load, unload, abort, error, select, change, submit, reset, focus, blur, resize, scroll events,
Event: 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
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 initalized, you can further customize it by adding specific attributes you may want to pass to the listening function:
evt.foo = "bar";
Once done, the event can be dispatched to the document or to a specific node:
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:
var target = document.getElementById("myTarget"); target.addEventListener("myEvent",myEventHandler,false);
Does you browser support custom JS events ?
Click to check.comments powered by Disqus