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
0
votes
0 answers

Check if td value has changed on reload of div

I'm attempting to detect if the state of each td element changes every 34 seconds. How it currently works: I have a PHP page that converts an array of data into a table On the page that displays the table, I have a Js file connected that refreshes…
user11276769
0
votes
1 answer

add an event listener to multiple elements that are not yet available on the dom

I have multiple selects in a table and I want to be able to change the options of al the selects on a column when I change the option of the select on the first row. The problem is that the selects are added dynamically. I managed to do this by…
0
votes
1 answer

jQuery.on('click') showing Window as value of $(this)

I have dynamically added content with data stored in jQuery's .data() cache. When the content is dynamically created there is also a dynamically created button for each div (Note that each generated div is storing the data mentioned above). When I…
prestondoris
  • 339
  • 4
  • 11
0
votes
1 answer

How do I do event delegation in Object Oriented JS?

I have trouble grabbing dynamically created DOM elements and I don't know where the subsequent click event delegation should take place (i.e. in my main .js file or inside the UI class). This object-oriented learning project sends async HTTP…
Adam
  • 375
  • 1
  • 4
  • 10
0
votes
1 answer

Retrieve the exact X/Y values of a
  • no matter where the mouse is clicked using Typescript
  • I'd really like some help on this...I'm blocked! OK, this is a simple easy question here but I'm missing one key component. This is my fiddle whereby I can "find" the item when I click on it but that's about…
    Peter The Angular Dude
    • 1,112
    • 5
    • 26
    • 53
    0
    votes
    0 answers

    Event Delegation Issue jQuery

    I have the below code, the first HTML snippet is loaded on the initial page load, then when the span with id flag is clicked the javascript will load the second HTML snippet into a hidden div on the webpage. Now this hidden div has a select drop…
    llanato
    • 2,508
    • 6
    • 37
    • 59
    0
    votes
    1 answer

    Why specify "document" or "body" BEFORE binding a jQuery event listener?

    In jQuery, there are numerous ways to bind actions to events, and to add listeners for them. With this I have no problem. But what I can't understand, is what would be the purpose of specifying "body" or "document" for that matter, before listening…
    cmprogram
    • 1,854
    • 2
    • 13
    • 25
    0
    votes
    1 answer

    JavaScript: How to get child element "i" classname using alongside event delegation?

    I'm recreating a classic card memory game for my final project - a deck of cards that I need to flip and match. An extract of the deck of cards in HTML is below:
    James
    • 3
    • 2
    0
    votes
    1 answer

    How to add onplay event to all html5 videos that are added dynamically to the page?

    I am trying the following code for adding onplay event to all the videos that are added dynamically to my page but it is not working! I tried with jQuery event-delegation but still not working, but I would prefer pure JavaScript solution. …
    Muhammad
    • 6,725
    • 5
    • 47
    • 54
    0
    votes
    1 answer

    React event handlers, delegation

    I saw some other posts on that but didn't understand. If I have a large table, with a clickable action button in each row. In jquery I would bind the event to the…
    user3599803
    • 6,435
    • 17
    • 69
    • 130
    0
    votes
    1 answer

    Event Delegation - cant change button class and value

    I'm trying to ban users and remove their bans using vanilla javascript. I'm using datatables, so I have to use event delegation to fire events.. But when I done with banning user, I can't change button class or value, how can I do that ?…
    Teoman Tıngır
    • 2,766
    • 2
    • 21
    • 41
    0
    votes
    1 answer

    How to check a dynamic checkbox and POST to ajax with delegation?

    I have checkboxes that are generated dynamically with value from database in a while statement as such : while($getplands = mysqli_fetch_assoc($getplanresults)){
    Sadie
    • 163
    • 10
    0
    votes
    1 answer

    Issues with event delegation on same container

    I have a function, simplified like this: var fooFunction = function($container, data) { $container.data('foobarData', data); $container.on('click', 'a', function(e) { var data = $(e.delegateTarget).data('foobarData'); var $target =…
    S Osten
    • 15
    • 1
    • 5
    0
    votes
    0 answers

    ajaxForm Event Delegation

    I have a form and i use ajaxForm to handle the submit, the problem is i can't submit the form twice after the first success(this works already) since it lost the event handler. I tried with event delegation but what i get is the default browser…
    Sergi
    • 743
    • 1
    • 9
    • 17
    0
    votes
    1 answer

    Android list tap event delegation

    I have a list that uses a database to display some data. There are several operations that the user can perform on each list item and instead of implementing a context menu where the user uses a long press to bring up a list of possible operations I…
    David K.
    • 6,153
    • 10
    • 47
    • 78