Generating DOM events from JavaScript

For the OnTime Group Calendar API Explorer I needed manipulate a dropdown element on the page using JavaScript which is easy enough but when doing it this way no onchange events are emitted which caused my page logic to break. Luckily for me there is a simple way to have the element emit an event using the dispatchEvent mechanism of the DOM. The element.dispatchEvent method is your friend here. The documentation shows you how to create a mouse event but I really needed a HTML based event. To create a such is done like below:

// get element
var elem = document.getElementById("some_dropdown");

// set selected option
elem.selectedIndex = 2;

// generate an 'onchange' event from 'elem'
var event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
event.eventName = "change";

One thought on “Generating DOM events from JavaScript”

  1.  createEvent and dispatchEvent don’t work on IE 8 and earlier, although those browsers do have their own equivalents.


    And that’s why God invented jQuery!  (Check out jQuery.trigger().)


Comments are closed.