I personally use a wrapper function to handle manually created events. The following code will add a static method on all Event
interfaces (all global variables ending in Event
are an Event interface) and allow you to call functions like element.dispatchEvent(MouseEvent.create('click'));
on IE9+.
(function eventCreatorWrapper(eventClassNames){
eventClassNames.forEach(function(eventClassName){
window[eventClassName].createEvent = function(type,bubbles,cancelable){
var evt
try{
evt = new window[eventClassName](type,{
bubbles: bubbles,
cancelable: cancelable
});
} catch (e){
evt = document.createEvent(eventClassName);
evt.initEvent(type,bubbles,cancelable);
} finally {
return evt;
}
}
});
}(function(root){
return Object.getOwnPropertyNames(root).filter(function(propertyName){
return /Event$/.test(propertyName)
});
}(window)));
EDIT: The function to find all Event
interfaces can also be replaced by an array to alter only the Event interfaces you need (['Event', 'MouseEvent', 'KeyboardEvent', 'UIEvent' /*, etc... */]
).