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/

Share:
30,438
Tyler
Author by

Tyler

Updated on March 21, 2021

Comments

  • Tyler
    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
    Tyler about 12 years
    By checking if (id.dispatchEvent) then else if (id.fireEvent) I can now use the non-ie8 code to work for ie9. Looks like IE is finally catching on?
  • Strelok
    Strelok about 12 years
    That's right. You can extract the firing code into a separate method that will handle all browsers.
  • Mike 'Pomax' Kamermans
    Mike 'Pomax' Kamermans over 11 years
    As 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.