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
3
votes
5 answers

difference between jQuery.live and jQuery.delegate

I have read some post about why do not use jQuery.live() and I want to check if I got it:) When I call $("body").delegate('element','click', function); Is it the same as $(element).live('click', function) ? In case of normal behaviour..According to…
simekadam
  • 7,334
  • 11
  • 56
  • 79
3
votes
1 answer

Vanilla JavaScript event delegation when dealing with Web Components

My current project uses web components (Custom Elements and Shadow DOM) which allow me to encapsulate complex logic and styles away from the Light DOM. Unfortunately, I've now hit a snag where I need to be able to switch out elements at will without…
michael
  • 4,427
  • 6
  • 38
  • 57
3
votes
2 answers

Event delegation with input oninput event

Is it somehow possible to set up oninput event delegation to change the text of the changeText div?
UkoM
  • 305
  • 2
  • 6
  • 17
3
votes
2 answers

How to find all events inside a container and delegate them

Suppose I have a markup like this
ABC
ABC
abc2
xys3
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
3
votes
1 answer

Binding jQuery handlers during the event capture phase (not event bubbling)

I'm looking to implement event delegation on blur/focus events, in a similar way to that suggested on quirksmode. As explained in TFA, blur and focus events don't bubble, so you can't use event delegation with them in the bubbling phase, but you…
El Yobo
  • 14,823
  • 5
  • 60
  • 78
3
votes
3 answers

Event Delegation in jQuery 1.4

I've got the following code: $("ul.relatedAlbums li").hover(function(){ $(this).css({fontWeight:"bold"}); }, function(){ $(this).css({fontWeight:"normal"}); }); I've heard good things about event delegation and speed performance. Using…
Matrym
  • 16,643
  • 33
  • 95
  • 140
3
votes
1 answer

Long press (hold) with jquery hammer.js 2 and event delegation

I recently upgraded to hammer.js 2 and one of the first things a I noticed was that "hold" has been replaced with "press". My old code worked fine with event delegation, but switching to press only seems to work when I put it on a specific…
Jools
  • 839
  • 8
  • 22
3
votes
3 answers

Is there a way to use jQuery's delegated event handler signature with multiple delegated targets?

I'm a big fan of using jQuery's delegated event handling signature: $('.container').on('click', '.button', function () { // do something }); I'm also a big fan of using the multiple event handler signature: $('.container').on({ click: function…
natlee75
  • 5,097
  • 3
  • 34
  • 39
3
votes
3 answers

Objects added dynamically to the DOM don't respond to jQuery Events

I have a table and I am adding rows to it dynamically, every one of the rows will have 2 cells, one of them will contain an input field where I plan to use the DatePicker UI to, obviously, pick a date. The issue comes when I add the new row, cells…
Annatar
  • 87
  • 6
3
votes
2 answers

Does jQuery class selector event binding attach eventHandler to each instance?

Im learning jQuery and when I read about $('.className').bind('click',function(){}) method one doubt arose. Does this method attach my event handler to each instance of className in the DOM? If so would it be a good approach -- like attaching an…
Ivin
  • 4,435
  • 8
  • 46
  • 65
3
votes
1 answer

How to solve flicker on iPad when event delegation is used?

When using the method of event delegation, we set the event handler on a higher level element (parent or grandparent), but this has an issue on iPad's Safari: if the parent element has a click handler, when the user touches anything inside this…
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
3
votes
2 answers

bounce animation using constructor?

I want to give a bounce animation to each individual hair on mouseover.the animation part is done on the first hair,but i don`t want to give events to each and every hair image. So here is my question,I am using constructor in my javascript code.Is…
user2412575
3
votes
1 answer

Remove dynamically generated

I am trying to a
when it is clicked. When I tried with .live() it shows me: object has no method live() I am using jQuery version 1.9, so live has been removed. $(document).ready(function(){ $('#addhelper').click(function(){ …
ketul shah
  • 413
  • 2
  • 7
  • 17
2
votes
3 answers

Global Javascript link handler

Here's what I have: A web application that runs in a single HTML page (call it myapp.req), with content coming and going via AJAX The application can be entered externally with a link such as myapp.req?id=123, and the application opens a tab with…
Sean Adkinson
  • 8,425
  • 3
  • 45
  • 64
2
votes
1 answer

How does one establish state-management in between a list of data-items and their element-node representatives in case of removing an item on 'click'?

I'm trying to initialize a remove button in order to remove an element from the DOM and its related data-item from its locally stored list. Below is the code which is supposed to display the properties of each data-item. let deltioItems =…