2

I have a problem with dispatching event in Internet Explorer 11. Currently, we have:

fireEvent for IE and

createEvent
initEvent
dispatchEvent

idiom for normal browsers.

The prorblem is that neither of these works in IE 11. Nor do the new way - using new Event() / new CustomEvent().

It looks like Microsoft deprecated their proprietary fireEvent (for IE 11) but did not offer support for correct dispatching.

PS. I believe i have read all topics here on SO related to the matter still can't find the working solution

2 Answers2

6

Here's a fully working solution I based on this SO Answer: https://stackoverflow.com/a/49071358/79677

You can use it like this: SendBrowserAgnosticEvent(myElement, 'change') and it will return the created Event object

Here's the code in JavaScript

/** This allows us to dispatch browser events in old IE and newer browsers */
export var SendBrowserAgnosticEvent = function(elem, eventName) {
    //Needed for IE Support: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#Browser_Compatibility
    //https://stackoverflow.com/a/49071358/79677
    var event;
    if (typeof(Event) === 'function') {
        event = new Event(eventName);
    } else {
        event = document.createEvent('Event');
        event.initEvent(eventName, true, true);
    }
    elem.dispatchEvent(event);

    return event;
};

and here it is in TypeScript with full typings

/** This allows us to dispatch browser events in old IE and newer browsers */
export const SendBrowserAgnosticEvent = <T extends HTMLElement | Window>(elem: T, eventName: string): Event => {
    //Needed for IE Support: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#Browser_Compatibility
    //https://stackoverflow.com/a/49071358/79677
    let event;
    if (typeof(Event) === 'function') {
        event = new Event(eventName);
    } else {
        event = document.createEvent('Event');
        event.initEvent(eventName, true, true);
    }
    elem.dispatchEvent(event);

    return event;
};
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
1

Answering my own question (thanks to the @LynnCrumbling for pointing out):

Browser specific event firing behavior better to replace with unified jQuery call like:

var eventObject = jQuery.Event("change"); // event you need to fire
$(targetObject).trigger(eventObject);