dispatchEvent in Chrome but not in IE11

JavascriptDom EventsInternet Explorer-11Dispatchevent

Javascript Problem Overview


I am using the following code to submit to a form:

element.dispatchEvent(new Event("submit"));

Inspector returns the error:

> Object doesn't support this action

This works in Chrome.

The purpose of this command is to make a division call the submit event on a form when clicked.

Jquery is not an option

Javascript Solutions


Solution 1 - Javascript

This is the best way to make it work for IE11 and other browsers with considering future changes.

var event;
if(typeof(Event) === 'function') {
    event = new Event('submit');
}else{
    event = document.createEvent('Event');
    event.initEvent('submit', true, true);
}

$el.dispatchEvent(event);

Solution 2 - Javascript

I just had the same problem, but the following seems to work in IE11:

var event = document.createEvent("Event");
event.initEvent("submit", false, true); 
// args: string type, boolean bubbles, boolean cancelable
element.dispatchEvent(event);

Solution 3 - Javascript

It's best to use a polyfil to fix this. (custom-event-polyfill)

# using yarn 
$ yarn add custom-event-polyfill

# using npm 
$ npm install --save custom-event-polyfill

then include/require it in your javascript

import 'custom-event-polyfill';

https://www.npmjs.com/package/custom-event-polyfill

Solution 4 - Javascript

I assembled bits and pieces of various approaches and got this to work:

var customEvent = document.createEvent('HTMLEvents');
customEvent.initEvent('myCustomEvent', true, true);
document.dispatchEvent(customEvent);

To be honest, this doesn't make a lot of sense to me. It creates an event (naming it HTMLEvents seems to be required) on the document, then goes and initializes that event with another name. If anyone can explain this better please add a comment below so it can be incorporated into the answer.

In any case, I'm able to listen to this custom event in IE11 (and modern browsers) with a standard event listener:

document.addEventListener('myCustomEvent', function(){
  console.log('Event received.');
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser4014674View Question on Stackoverflow
Solution 1 - JavascriptKohei MikamiView Answer on Stackoverflow
Solution 2 - JavascriptTaimo KolsarView Answer on Stackoverflow
Solution 3 - JavascriptSanathView Answer on Stackoverflow
Solution 4 - JavascriptMike WheatonView Answer on Stackoverflow