Why does .fireEvent() not trigger in IE9?
30,438
In IE versions >= 9 and all other browsers you should use the dispatchEvent
method:
var event = document.createEvent("HTMLEvents");
event.initEvent("change",true,false);
document.getElementById("id").dispatchEvent(event);
Check out http://jsfiddle.net/QKsvv/
Author by
Tyler
Updated on March 21, 2021Comments
-
Tyler about 3 years
Rather frustrating time here with IE9. This code works in IE7/8, but not 9.
document.getElementById('id').fireEvent("OnChange");
Any insight as to why?
-
Tyler about 12 yearsBy checking
if (id.dispatchEvent)
thenelse if (id.fireEvent)
I can now use the non-ie8 code to work for ie9. Looks like IE is finally catching on? -
Strelok about 12 yearsThat's right. You can extract the firing code into a separate method that will handle all browsers.
-
Mike 'Pomax' Kamermans over 11 yearsAs additional information, this only works for elements that are in the live DOM. If you dynamically make objects and want to simulate things like clicks on them using dispatchEvent, you have to add them to the DOM first. If you don't, you can still dispatch events, but you'll be tearing your hair out wondering why the function runs successfully without triggering your event handler.