Skip to content

Instantly share code, notes, and snippets.

@cwchentw
Last active October 11, 2020 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwchentw/7cf881e138f58bda68b010b2faf54465 to your computer and use it in GitHub Desktop.
Save cwchentw/7cf881e138f58bda68b010b2faf54465 to your computer and use it in GitHub Desktop.
Utility Function for Cross-browser Scripting in Vanilla JavaScript
/* Utility to add an event listener for an element. */
function addEvent (event, elem, func) {
if (elem.addEventListener)
elem.addEventListener(event, func, false);
else if (elem.attachEvent)
elem.attachEvent('on'+event, func);
else
elem[event] = func;
}
/* Utility to load JavaScript code when the page is ready. */
function loadContent (callback) {
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', function (ev) {
callback(ev);
}, false);
}
else {
document.attachEvent('onreadystatechange', function (ev) {
if ('complete' === document.readyState)
callback(ev);
});
}
}
/* Polyfill of event.preventDefault function. */
if (!Event.prototype.preventDefault) {
Event.prototype.preventDefault = function () {
this.returnValue=false;
};
}
/* console shim for old Internet Explorers */
(function () {
if ("undefined" === typeof window["console"]) {
window.console = {
log: function () {},
info: function () {},
warn: function () {},
debug: function () {},
error: function () {}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment