Skip to content

Javascript custom event handling in IE

Events can be extremely useful in Javascript, and most browsers implement them naively. Here is an example of an event that fires when the number of vehicles change.

//Create the event
var vehicleCountEvent = new CustomEvent("vehicleCount:change", { "detail": newVehicleCount });

//Fire the event
document.dispatchEvent(vehicleCountEvent);

//Process the event
document.addEventListener("vehicleCount:change", function (event) {
     $('#myVehicleCount').html(event.detail);
});

This will work on every single browser, except IE. It even works on edge.  If you run this in IE 11 or lower you will receive an “Object does not support this action error”.  To get around this there are two options. JQuery or using a polyfill.

For simplicity, cross browser support and the general pervasiveness of JQuery, the first approach is generally the best approach.  You can implement the equivalent above code as below.

//Create the event
 var vehicleCountEvent = $.Event("vehicleCount:change");
 vehicleCountEvent.vehicleCount = newVehicleCount;

//Fire the event
 $(document).trigger(vehicleCountEvent);

//Process event
$(document).on("vehicleCount:change", function (event) {
     $('#myVehicleCount').html(event.vehicleCount);
});

Another day, another IEism.

Published inJavascript

Comments are closed.