Last active
October 11, 2020 08:14
-
-
Save cwchentw/7cf881e138f58bda68b010b2faf54465 to your computer and use it in GitHub Desktop.
Utility Function for Cross-browser Scripting in Vanilla JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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