Skip to content Skip to sidebar Skip to footer

How To Decrease The Number Of `addeventlistener` Using Event Delegation. Javascript

Is it possible to have just one addEventListenerusing Event Delegation

Solution 1:

Especially when dealing with dynamic content, binding event handlers directly to the newly inserted elements gets very resource hungry, it affects your runtime behavior negatively.

What you can do, is bind an event handler to a common ancestor element (such as a wrapping div or even the document.body. All you need to do, is giving each element that has to be activated on your event a separate class name to identify them properly.

Example:

<body><divclass="clickactive"><imgsrc="..."></div><!-- ... some more dynamic "clickactive" elements --></body>

In your js, you just do something like this:

$(document.body).click(function(e){
    if ($(e.target).closest(".clickactive").length > 0){
       // handle your click on $(e.target).closest[0]
    }
}

That way, you

  • don't need to worry about applying your event handler over and over again for every newly inserted element
  • you only have one event handler activated

The downside, however (especially when binding to the body): Your click gets called every time any element is clicked within the element you bound the event handler to (of course, the condition is false and that code is not executed, but the condition is evaluated anyway). So best practice is to bind to the closest common ancestor.

Post a Comment for "How To Decrease The Number Of `addeventlistener` Using Event Delegation. Javascript"