I need to create a Custom Event which will pass some data to the event listener. I already created one like below
CustomEvent
var event = new CustomEvent('store', { 'detail': obj });
document.getElementById("Widget").dispatchEvent(event);
Listener
document.getElementById("Widget").addEventListener('store', function (e) {
console.log(e.detail);
document.getElementById("result").innerHTML = e.detail.name+"<br>"+e.detail.address;
}, false);
It is working fine in browsers such as Chrome and Firefox but not working in IE11. I am getting an error in IE:
Object doesn't support this action
CustomEvent is not working in IE.
How can I make this cross-browser compatible ? I don't want to use jQuery trigger()
because the Listener
might not be in a page having jQuery
CoustomEvent constructor is not supported in IE11. you can use following pollyfill
(function () {
if ( typeof window.CustomEvent === "function" ) return false;
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
Copied from MDN
Take a look to the "Can I use" page and what it says about the Custom Events.
http://caniuse.com/#feat=customevent
Specifically, read this quote:
While a window.CustomEvent object exists, it cannot be called as a constructor. Instead of new CustomEvent(...), you must use e = document.createEvent('CustomEvent') and then e.initCustomEvent(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With