Questions tagged [event-delegation]

In JavaScript, event delegation is a concept of listening to specific events on some element (eg. the whole document) to catch these events being fired on any of the child elements, even the ones that did not exist when the event was being attached. This happens thanks to another concept called "event bubbling", which makes events to be visible by parent elements. Within every event handler it is possible to check what was the target element of the event.

You might use this tag if your question sounds like one of these:

  • I dynamically inserted/modified nodes in my document, and now they don't handle events.
  • How can I bind event handlers for nodes that don't exist yet?
  • I'm binding thousands of event handlers in my document, and now it runs super slow.
  • I need to bind the same event handler to lots of different elements. Isn't there an easier way?

If so, then you might want to use event delegation. The advantages of delegation are:

  1. Use a single handler to capture many events on many different nodes.
  2. Support dynamic page changes without having to constantly re-bind event handlers.

To understand delegation, you first have to be familiar with event bubbling.

Bubbling

Many of the most common events in JavaScript "bubble" up the DOM tree. For example, consider the following HTML:

<div id="imageDiv">
    <img src="/abc.png" class="clickable"/>
    <img src="/def.png" class="clickable"/>
    <img src="/ghi.png" class="clickable"/>
    <p>
        <img src="/jkl.png" class="clickable"/>
    </p>
</div>

If a user clicks on the jkl.png image the click event will be fired first on the image itself, then on the containing paragraph, then on the div element, and so on all the way up to the document object.

Read more about Event Bubbling

An excellent article on Bubbling vs Catching

Delegation

You can take advantage of event bubbling to implement a single handler for a large number of nodes.

Instead of binding four click event handlers (one for each image), you only need one handler attached to the div element. The event object contains information about which element originally received the event (the target). You can test the target to find out if you should handle the event or not.

Here we bind a click handler to div#imageDiv and use it to handle click events on the descendant images:

document.getElementById('imageDiv').onclick = function(evt) {
    if (evt.target.className == 'clickable') {
        // ... do something here ...
    }
};

Now your single handler will catch all of the click events for all of the images inside div#imageDiv. Also, you can add images to div#imageDiv dynamically and not have to worry about binding new click handlers for them.

Of course there are browser compatibility issues with how some events bubble, and with finding the original target of the event. That is why a good JavaScript library will give you a convenient command for delegation. jQuery provides the on() method:

$('#imageDiv').on('click', 'img.clickable', function(evt) {
    // ... "this" is the image that was clicked ...
});
325 questions
1
vote
1 answer

click Event is not delegated in chrome

In my application I create some new elements and append them to the page according to use's operation, var dv=document.createElement('div'); //set styles for the dv ..... After create this div element, I will add some event to…
hguser
  • 35,079
  • 54
  • 159
  • 293
1
vote
2 answers

what is best practice when removing elements with handlers?

I encountered an issue using jQuery's .delegate() method on IE8 when removing the elements to which my delegate handler was attached. Here's the scenario: I had a table with rows that each had a delete button. The rows were created dynamically, so…
kinakuta
  • 9,029
  • 1
  • 39
  • 48
1
vote
5 answers

Event bubbling for event delegation

I am trying to implement event delegation with the following code:
1
vote
2 answers

Does ActionScript 3 have some sort of event delegation system?

I have a container with many images. Instead of adding a listener for click and other mouse events on each of the images, I would like to only listen for those events on the parent of the image. Is that possible?
Francisc
  • 77,430
  • 63
  • 180
  • 276
1
vote
1 answer

YUI3 event delegation not working in FF2

I am using YUI 3.3.0. Event delegation not working in FF2. Any clue ? Thanks in advance. container.delegate("click", function(e) { alert("hi"); //alerts except in FF2 },"td, li");
Aneesh
  • 1,193
  • 3
  • 16
  • 26
1
vote
3 answers

Remove click event on specific element where the event is called in multiple places

I have multiple card generated from a loop which share the same functionality. One of them is to Like and Dislike buttons. It's someone's code, I was asked to remove the click event per card once the user click on Like/Dislike button. I don't know…
1
vote
0 answers

How to delegate blur event?

Is it possible to delegate blur event? I have this code and want to add only one event listener to whole div where are my inputs: const inputs = document.querySelectorAll('div.div input[type="number"]'); inputs.forEach(input => { …
EzioMercer
  • 1,502
  • 2
  • 7
  • 23
1
vote
2 answers

Problem with attaching onClick event to dynamically created buttons in list of items. (React v18)

I have a list of dynamically generated items with information about real estate objects. Every item has a button. When clicked a contact form pops up. However when a button is clicked the event fires on all of the items in the list instead of only…
1
vote
0 answers

Change Blur events with javascript event delegation

I have a form that is dynamically added to the DOM and therefore I have to use event delegation. I can not get this to fire and it looks to me like this event can only be attached to an input element ['change', 'blur'].forEach(event => { …
dbzx10299
  • 722
  • 2
  • 14
1
vote
2 answers

Populate next empty text input based on a button click

I have a simple set of buttons that may be clicked in any order. When clicked the button should fill the next available text box. So far I have only been able to make the button click populate the text box that is in focus. This only really fulfils…
1
vote
2 answers

Why compare element to this keyword?

I am looking at the following link which is a part of event delegation documentation. In the link, we have the followig let table = document.getElementById('bagua-table'); let selectedTd; table.onclick = function(event) { let target…
Jeff Benister
  • 468
  • 3
  • 12
1
vote
1 answer

How to bind each array item to its element node representation and make the nodes watch the array?

I have an array, and I want to print them in div tags, and also when I make changes on the array, I want the change also to occur on divs (for example when I delete an item, div print of item also be deleted; or change the value of an item, expect…
1
vote
4 answers

why remove function is not working in event delegation in javascript?

I want to remove h1 tag when clicked on refresh btn but it doesn't remove h1 tag but when i run same code by using addeventlistener on each btn it run. but not run in delgation . var wrapper =…
1
vote
1 answer

on click event not working after append tbody in ajax call?

I am using php and mysql with jquery to display my data. The initial time my on click event is working on tbody. But when I append tbody with ajax call it's not working. I am using event delegation with .on My html table : I am using simple html…
amit sutar
  • 541
  • 2
  • 11
  • 37
1
vote
1 answer

How do I make my accordion/collapsible work with event delegation?

I want to create an accordion in my webshop's cart drawer but I can't find a way to fix my issue. What is happening here is that I get the element but as soon as the drawer is re-rendered then my reference is lost. Because the DOM dynamically…
Maurice
  • 11
  • 2