Last active
June 7, 2018 18:29
-
-
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'}})`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
); | |
} |
line 10: var event = document.createEvent(eventName);
causes "Object doesn't support property or method 'createEvent'" in IE8.
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
For IE8 this works well together with my ie8 normalizer which will take care of adding
stopImmediatePropagation
too to the prototype.