Last active
August 3, 2016 13:42
-
-
Save chodorowicz/daa58fab1ba07f025925468262e37f0b to your computer and use it in GitHub Desktop.
JavaScript DOM events
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
/** 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); | |
} | |
}; |
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
<!-- 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