Introduction
Event
delegation is one of the very good methodologies present in the JavaScript
platform. Event Delegation provides an option to programmers to avoid adding an event
listener to every specific node. By the use of JavaScript Event Delegation the
event listener is to be added to only one parent. And that parent analyzes
events to find a match on a child element.
Example
Suppose we
have a parent OL element with some child elements:
- <ol id="parent-list">
- <li id="p1">ItemNumber 1</li>
- <li id="p2">ItemNumber 2</li>
- <li id="p3">ItemNumber 3</li>
- <li id="p4">ItemNumber 4</li>
- <li id="p5">ItemNumber 5</li>
- <li id="p6">ItemNumber 6</li>
- </ol>
May be sometime a task need to happen where each child is clicked. The
programmer can add a separate event listener to each individual LI element, and
also if LI elements are frequently added and removed from the ordered list, then
frequently adding and removing event
listener will be tough work. The
programming solution for this will be to add an event listener to the parent
and when the event bubbles up to the OL element, programmer check the event
object's target property to get the reference of the actual clicked node.
JavaScript snippet to explain Event
Delegation
- document.getElementById ("parent-list").addEventListener("click",function(ev) {
-
-
- if(ev.target && ev.target.nodeName == "LI") {
-
- console.log("List item ",e.target.id.replace("post-")," was clicked!");
- }
- });