Skip to content

Instantly share code, notes, and snippets.

@frequent
Created October 9, 2013 17:00
Show Gist options
  • Save frequent/6904575 to your computer and use it in GitHub Desktop.
Save frequent/6904575 to your computer and use it in GitHub Desktop.
Custom Event handler for IE8+
var util = {};
/**
* IE8 compatible custom event listener
* @method listenToCustomEvents
* @param {string} eventName Event to listen for
* @param {method} callback Method to run on event
*/
util.listenToCustomEvents = function (event_name, callback) {
if (document.addEventListener) {
document.addEventListener(event_name, callback, false);
} else {
document.documentElement.attachEvent('onpropertychange', function (e) {
if(e.propertyName == event_name) {
callback();
}
});
}
};
/**
* IE8 compatible custom event trigger
* @method triggerCustomEvent
* @param {string} eventName Event to listen for
*/
util.triggerCustomEvent = function (event_name) {
var event;
if (document.createEvent) {
event = document.createEvent('Event');
event.initEvent(event_name, true, true);
document.dispatchEvent(event);
} else {
event = document.documentElement[event_name];
event += 1;
}
};
/**
* IE8 compatible removal of event listeners
* @method triggerCustomEvent
* @param {string} eventName Event to listen for
*/
util.removeCustomEvent = function (event_name, callback) {
if (document.removeEventListener) {
document.removeEventListener(event_name, callback, false);
} else {
document.documentElement.detachEvent('onpropertychange', callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment