Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 13, 2020 02:54 pm GMT

How JavaScript Event Delegation Works

Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent.

For Example - Let's say that we have a parent UL element with several child elements:

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

Now something needs to be done when li element is clicked one way is to attach event listener to all the li elements but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app.

The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?

Simple: 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.

Javascript snippet

// 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!");    }});

Hopefully this helps you visually the concept behind event delegation and convinces you of delegation's power!


Original Link: https://dev.to/prkkhan786/how-javascript-event-delegation-works-50j7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To