Last active
August 29, 2015 14:06
-
-
Save janez89/c9631a9d76fdf508b95b to your computer and use it in GitHub Desktop.
native js addEventListener
This file contains 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
// By Janez | |
function addEventListener(elOrId, event, callback, useCaptrue) { | |
if (typeof elOrId === 'string') { | |
var elName = elOrId; | |
elOrId = document.getElementById(elOrId); | |
if (!elOrId) { | |
console.error('"'+ elName +'" ID not found!'); | |
return; | |
} | |
} | |
if ('addEventListener' in elOrId) | |
elOrId.addEventListener(event, callback, useCaptrue || false); | |
else if ('attachEvent' in elOrId) | |
elOrId.attachEvent('on'+ event, callback); | |
} | |
// usage | |
addEventListener('id', 'click', function (e) { ... }); | |
// or | |
addEventListener(document.getElementById('id'), 'click', function (e) { ... }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment