Skip to content

Instantly share code, notes, and snippets.

@greut
Created November 26, 2008 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save greut/29390 to your computer and use it in GitHub Desktop.
Save greut/29390 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<title>Event delegation</title>
<ul>
<li><a href="#a">a</a></li>
<li><a href="#b"><span>b</span></a></li>
<li><a href="#c"><span><span>c</span></span></a></li>
<li><a href="#d"><span><span><span>d</span></span></span></a></li>
</ul>
<script>
// see the previous versions for the recursive (and brilliant) way ;-)
document.getElementsByTagName("ul")[0].addEventListener("click", function(event) {
var target = event.target;
while(target != this && target.nodeName.toLowerCase() !== "a") {
target = target.parentNode
}
if(target != this){
alert(target.getAttribute("href").substring(1));
event.stopPropagation();
event.preventDefault()
}
}, false);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment