Skip to content

Instantly share code, notes, and snippets.

@jtwalters
Last active November 16, 2016 22:04
Show Gist options
  • Save jtwalters/86900fa3c629f0d0adf0 to your computer and use it in GitHub Desktop.
Save jtwalters/86900fa3c629f0d0adf0 to your computer and use it in GitHub Desktop.
Cross browser addEvent function (window load, ready, etc.)
(function () {
//////////////////////////////
// Add event (cross browser)
// From http://stackoverflow.com/a/10150042
//////////////////////////////
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent('on' + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
// Example usage
addEvent(window, 'load', function () {
var $ = window.jQuery;
// Do something
});
addEvent(document, 'DOMContentLoaded', function () {
var $ = window.jQuery;
// Do something
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment