Skip to content

Instantly share code, notes, and snippets.

@chodorowicz chodorowicz/events.js
Last active Aug 3, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.