Skip to content

Instantly share code, notes, and snippets.

@nobitagit
Created June 16, 2014 14:29
Show Gist options
  • Save nobitagit/5dcbf5e92b22a526499e to your computer and use it in GitHub Desktop.
Save nobitagit/5dcbf5e92b22a526499e to your computer and use it in GitHub Desktop.
Proper Js event delegation, handling parents of clicked elements
/*
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