Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active June 7, 2018 18:29
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save WebReflection/6693661 to your computer and use it in GitHub Desktop.
Save WebReflection/6693661 to your computer and use it in GitHub Desktop.
CustomEvent for IE8 or other old browsers that do not implement it. `new CustomEvent('type', {bubbles:true, detail:{what:'ever'}})`
try{new CustomEvent('?')}catch(o_O){
/*!(C) Andrea Giammarchi -- WTFPL License*/
this.CustomEvent = function(
eventName,
defaultInitDict
){
// the infamous substitute
function CustomEvent(type, eventInitDict) {
var event = document.createEvent(eventName);
if (type != null) {
initCustomEvent.call(
event,
type,
(eventInitDict || (
// if falsy we can just use defaults
eventInitDict = defaultInitDict
)).bubbles,
eventInitDict.cancelable,
eventInitDict.detail
);
} else {
// no need to put the expando property otherwise
// since an event cannot be initialized twice
// previous case is the most common one anyway
// but if we end up here ... there it goes
event.initCustomEvent = initCustomEvent;
}
return event;
}
// borrowed or attached at runtime
function initCustomEvent(
type, bubbles, cancelable, detail
) {
this['init' + eventName](type, bubbles, cancelable, detail);
'detail' in this || (this.detail = detail);
}
// that's it
return CustomEvent;
}(
// is this IE9 or IE10 ?
// where CustomEvent is there
// but not usable as construtor ?
this.CustomEvent ?
// use the CustomEvent interface in such case
'CustomEvent' : 'Event',
// otherwise the common compatible one
{
bubbles: false,
cancelable: false,
detail: null
}
);
}
@WebReflection
Copy link
Author

For IE8 this works well together with my ie8 normalizer which will take care of adding stopImmediatePropagation too to the prototype.

@AJ-Tucker
Copy link

line 10: var event = document.createEvent(eventName); causes "Object doesn't support property or method 'createEvent'" in IE8.

@alrik11es
Copy link

Is @AJ-Tucker comment true? I can't reproduce it. For me the code works, and works as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment