Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chodorowicz
Last active August 3, 2016 13:42
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 chodorowicz/daa58fab1ba07f025925468262e37f0b to your computer and use it in GitHub Desktop.
Save chodorowicz/daa58fab1ba07f025925468262e37f0b to your computer and use it in GitHub Desktop.
JavaScript DOM events
/** attach event diretly to DOM element */
var myelement = document.getElementById('my-div');
myelement.onclick = function() {
alert('Ouch!');
}
/** add event listener */
var mypara = document.getElementById('my-div');
mypara.addEventListener('click',
function() {alert('Boo!')},
false
);
/**
* old IE compatible attaching
* @param {object} el - DOM element to attach event
* @param {string} type - click, mouseover, etc...
* @param {function} handler - function to execute
**/
function addEvent(el, type, handler) {
if (el.addEventListener) {
el.addEventListener(type, handler);
} else {
el.attachEvent(`on${type}`, handler);
}
};
<!-- attach event directly in HTML -->
<div onclick="alert('Ouch!')">click</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment