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

preventDefault() is insufficient in anchor event delegation in iframe?

I hope this might be a low-hanging fruit for all you web-dev experts out there: I have implemented event delegation by attaching a mouse click handler to a parent element of an unordered list of anchor elements (classic navigation design). The…
2
votes
1 answer

jQuery delegate performance on the click event on large lists - slows down if you dynamically add more elements?

I have a visual list of items like this: http://jsfiddle.net/viatropos/XCe3T/1/ In the real app, I'm only loading 200 total items. But the problem is the click event takes almost one second to call the handler, even with just 200 items. The…
Lance
  • 75,200
  • 93
  • 289
  • 503
2
votes
2 answers

JS Jquery How to select a mouse click Target > parent > .Class

I currently have a table set up where each cell in the body looks like `

?

${response[j].clues[i].question}

I am needing to make just the div.null…
2
votes
4 answers

How does one handle DOM events from various buttons by a single handler function

I'm not sure if it's possible, but I'd like to use one unique function to trigger 4 different buttons to count a value (+ and -). But there are four different span values, for example, if I trigger forest it will only add or remove from forest, if I…
2
votes
1 answer

How to do Event delegation for an Array?(or NodeList)

I'm trying to use the Event delegation/switch statement for the first time in my life, and I'm having trouble with for loop. When it was 'array[i]' it wasn't a problem. But now I'm removing the for loop to use the event delegation and putting it…
user13670138
  • 201
  • 2
  • 7
2
votes
2 answers

Jquery hide and delete image after append and upload

I am trying to hide and delete image, this is the append code after upload Append code $('#uploaded_images').append('
Otávio Barreto
  • 1,536
  • 3
  • 16
  • 35
2
votes
1 answer

JQuery - Event Delegation - What is happening in my code?

I've read as much as I can on event delegation, and I cannot figure out why my code is acting the way it is. When the page loads, all of the check buttons work properly (toggles between 2 classes). Whenever I add a new item to the shopping list, the…
2
votes
1 answer

Why should I use event delegation instead of queryselectorAll

I'm learning JavaScript and crossed over Event Bubbling and Event Delegation. I know what Event Bubbling is (goes from a child until Window Object), but I saw that everybody says that Event Delegation is the opposite, and they do some If statements…
2
votes
0 answers

Angular 4 Event Delegation

I am required to detect a click event on a pseudo-element (::after) which holds an icon in CSS. This pseudo-element is a sibling of a . I am propagating the…
David Casanellas
  • 815
  • 2
  • 11
  • 18
2
votes
2 answers

How to set event delegations on iframe load events in jquery?

In jquery, I want to do this basically: $(window).on('load', 'iframe', function() { alert(this); }); Is this possible to do? I want to run a function anytime a iframe is dynamically added to DOM and it finishes loading.
omega
  • 40,311
  • 81
  • 251
  • 474
2
votes
2 answers

Click event not working in javascript

I Follow This Article for Impalement CRUD Operation with HTML5 and Javascript. So that Submit Data to Local Storage and save it. my problem is Delete and Edit Operation when clicking on delete and edit button Nothing…
Soheil Alizadeh
  • 2,936
  • 11
  • 29
  • 56
2
votes
0 answers

How does one stop propagation of event to a global listener in a React component?

I have a component that should listen all mousedown events on my page document.addEventListener('mousedown', listener) Now let's suppose I have a button in my React app
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
2
votes
1 answer

click.delegate for ul items in AureliaJS

Given ul list defined as below:
  • ${suggestion.name}
How do I pass suggestion object to onListItemClick? I know I can put click.delegate…
Marek M.
  • 3,799
  • 9
  • 43
  • 93
2
votes
1 answer

Using Event Delegation, why is the eventPhase 0, meaning None?

I tried out event delegation and checked the eventPhase of the event object. Surprisingly, it showed 0 meaning Event.NONE explained as "No event is being processed at this time" as defined on Mozilla's eventPhase description. This is true in the…
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
2
votes
0 answers

How to delegate scroll event

I am aware of the fact that jquery doesn't support delegate scroll event. So I would like to know the right way of doing it? jQuery(document).scroll(function () { var st = jQuery(this).scrollTop(); if (st < lastScrollTop)//if…
Varun Hegde
  • 349
  • 2
  • 12