1

This function below doesn't work on IE11, because IE11 is not supporting dispatchEvent and CustomEvent.

How can I convert this function to let it work on IE11?

I tried to add a variable which returns true/false if the browser is IE11, and based on that disable the dispatchEvent code. But that didn't work.

Any ideas how I can let this code work on IE11?

 function disableLoader(dataElement) {
    const dataElement = document[0].querySelector('[data-id]');
    const dataElementId = dataElement.getAttribute('data-id');

    dataElement.dispatchEvent(new CustomEvent('dataLoaded', {
        detail: {
            dataId: dataElementId,
            status: 'finished'
        }
    }));
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
can
  • 214
  • 2
  • 14

2 Answers2

2

You can polyfill the CustomEvent() constructor functionality in Internet Explorer 9 and higher with the following code:

    (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;
    })();

More detail information, please check the CustomEvent() constructor and this sample code. The sample output as below:

enter image description here

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
0

Your question seems to have been already answered over here: IE 11 DispatchEvent. You could, also, make use of a polyfill such as this https://github.com/Hooked74/events-polyfill. As for passing details, you need to call the yourevent.initCustomEvent() method passing the details object as your last argument before dispatching as described by its documentation: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/initCustomEvent.

  • https://stackoverflow.com/questions/27643181/ie-11-dispatchevent but this one is not a CustomEvent. – can Nov 25 '19 at 14:47
  • When you use `Document.createEvent()` you may not have a event that is created using the CustomEvent class, but you do get a custom event. The logic in your algorithm, however, will need to be slightly changed to accomodate this older way of creating custom events. If you go for the polyfill route, though, you get to have a simpler function on your source code, instead of using differing logic based on a condition around which browser it's being executed on. – Victor Oliveira Nov 25 '19 at 14:57