Skip to content

Instantly share code, notes, and snippets.

@okiwan
Created April 17, 2014 10:35
Show Gist options
  • Save okiwan/10972411 to your computer and use it in GitHub Desktop.
Save okiwan/10972411 to your computer and use it in GitHub Desktop.
JavaScript event delegation example
window.onload = function() {
if(document.body.addEventListener) {
document.body.addEventListener('mouseover', onMouseOverHandler, false);
document.body.addEventListener('mouseout', onMouseOutHandler, false);
} else {
document.body.attachEvent('onmouseover', onMouseOverHandler);
document.body.attachEvent('onmouseout', onMouseOutHandler);
}
function switchImage(e, o) {
var srcstr = '.png', dststr = '-sel.png';
if(!o) dststr = [srcstr, srcstr = dststr][0];
var myE = e.children[0];
myE.setAttribute('src', myE.getAttribute('src').replace(srcstr, dststr));
}
function onMouseOverHandler(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
if (target.className.match(/menu-item-link/)) {
switchImage(target, 1);
}
}
function onMouseOutHandler(e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (target.className.match(/menu-item-link/)) {
switchImage(target, 0);
}
}
}
@okiwan
Copy link
Author

okiwan commented Apr 17, 2014

HTML code missing. This is just to get an idea (review in case of c&p).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment