Created
April 17, 2014 10:35
-
-
Save okiwan/10972411 to your computer and use it in GitHub Desktop.
JavaScript event delegation example
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
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
HTML code missing. This is just to get an idea (review in case of c&p).