Skip to content

Instantly share code, notes, and snippets.

@janez89
Last active August 29, 2015 14:06
Show Gist options
  • Save janez89/c9631a9d76fdf508b95b to your computer and use it in GitHub Desktop.
Save janez89/c9631a9d76fdf508b95b to your computer and use it in GitHub Desktop.
native js addEventListener
// 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