Created
June 16, 2014 14:29
-
-
Save nobitagit/5dcbf5e92b22a526499e to your computer and use it in GitHub Desktop.
Proper Js event delegation, handling parents of clicked elements
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
/* | |
Proper event delegation without targeting errors | |
Given the structure: | |
<ul> | |
<li><div class="d"></div></li> | |
<li><div class="d"></div></li> | |
<li><div class="d"></div></li> | |
<li><div class="d"></div></li> | |
<li><div class="d"></div></li> | |
<li><div class="d"></div></li> | |
</ul> | |
we can write: | |
el.addEventListener('click', function(e){ | |
var el = e.target; | |
if (e.tagName === 'li'){ | |
....... | |
} | |
}); | |
But we can't be sure the div will not intercept the click we want be | |
attached to the <li>. | |
See also: http://stackoverflow.com/a/9915763/1446845 | |
*/ | |
document.getElementById('dom').addEventListener('click', function(e){ | |
var el = e.target; | |
while (el && el.tagName !== 'LI'){ | |
el = el.parentNode | |
} // note that this will go up even past the listener | |
console.log(el) | |
}, false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment