Skip to content

Instantly share code, notes, and snippets.

@Vanderln
Created June 9, 2013 15:41
Show Gist options
  • Save Vanderln/5743987 to your computer and use it in GitHub Desktop.
Save Vanderln/5743987 to your computer and use it in GitHub Desktop.
Javascript demo of event delegation. http://jsfiddle.net/6w5mx/
// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click",function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.nodeName == "LI") {
// List item found! Output the ID!
alert("List item " + e.target.id.replace("post-", "") + " was clicked!");
}
});
<ul id="parent-list">
<li id="post-1">Item 1</li>
<li id="post-2">Item 2</li>
<li id="post-3">Item 3</li>
<li id="post-4">Item 4</li>
<li id="post-5">Item 5</li>
<li id="post-6">Item 6</li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment