EVENT DELEGATION SIMPLIFIED?

Event delegation simplified?

  • First let’s understand few terms in Event model in JS. When an event is trigged on an element (say a click on a button), then such event goes UP to all it’s ancestors elements and triggers “click” on all of button’s parents.

<body onclick=”alert(“I am the body”)>
<section onclick=”alert(“I am a section”)>
<div>
<button onclick=”alert(“I am a button”)>-
Click Me</button>
</div>
</section>
</body>

Clicking on the button will show up 3 alert boxes in the following order:

I am a button
I am a Section
I am the body

Whether an onclick is attached on each of it’s ancestors elements or not, the “click” event is fired on each of them. This is event bubbling. The “clicked” element (in this case button) is stored in ‘target’ property of the event object.

Now the event delegation:

  • Let’s say that we wanted to have a click event to each list item <li> element below. Instead of adding an event to each <li> element, we add the event at the parent level (ul in this case). The reason is that whenever a list item is clicked, the event bubbles up to top of DOM tree. When this happens, we can capture the event at UL (event bubbling) and easily determine from which element the event originated and perform the functionality to that element.

<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>

  • When the event bubbles up to the UL element, you check the event object’s target property to gain a reference to the actual clicked node.
  • JS Example

// 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!
console.log(“List item “, e.target.id.replace(”
post-“),” was clicked!”);
}
});

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>