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

Delegation: EventEmitter or Observable in Angular

I am trying to implement something like a delegation pattern in Angular. When the user clicks on a nav-item, I would like to call a function which then emits an event which should in turn be handled by some other component listening for the…
the_critic
  • 12,720
  • 19
  • 67
  • 115
267
votes
10 answers

What is DOM Event delegation?

Can anyone please explain event delegation in JavaScript and how is it useful?
Xenon
  • 2,687
  • 3
  • 16
  • 4
32
votes
2 answers

Vanilla JS event delegation - dealing with child elements of the target element

I'm trying to do event delegation in vanilla JS. I have a button inside a container like this
And Finally
  • 5,602
  • 14
  • 70
  • 110
30
votes
7 answers

How to stop event bubbling with jquery live?

I am trying to stop some events but stopPropagation does not work with "live" so I am not sure what to do. I found this on their site. Live events do not bubble in the traditional manner and cannot be stopped using stopPropagation or …
chobo2
  • 83,322
  • 195
  • 530
  • 832
20
votes
6 answers

Native JS equivalent to jQuery delegation

What is the native implementation for event delegation on dynamically created dom elements? I tried looking at the jQuery source but I can't follow the .on method. Note: Currently I attach the event handlers after the dom elements are created, which…
Scott Mitchell
  • 698
  • 4
  • 11
19
votes
2 answers

Event delegation vs direct binding when adding complex elements to a page

I have some markup like this (classes are just for explication):
  1. Top-Line Info
slk
  • 285
  • 1
  • 2
  • 8
14
votes
2 answers

JavaScript: How to simulate change event in internet explorer (delegation)

UPDATE: (recap, fiddle and bounty) This question hasn't been getting too much attention, so I'm going to spend some rep on it. I know I tend to be overly verbose in both my answers and questions. That's why I went ahead and set up this fiddle, which…
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
13
votes
2 answers

Selecting text behind another element with createEvent

I have a scenario where I have some text, which should be user-selectable. The problem is, that there's an UI overlay on top of it, which prevents selecting text by default. The logical way to keep the overlay and still be able to select the text,…
zatatatata
  • 4,761
  • 1
  • 20
  • 41
13
votes
2 answers

mouseenter delegation using vanilla JavaScript?

How do I implement event delegation for the mouseenter event? I'm looking for the equivalent to this jQuery code, but didn't manage to understand how jQuery does it internally: $(document).on('mouseenter', '.demo', foo); I've seen this other…
Alvaro
  • 40,778
  • 30
  • 164
  • 336
13
votes
5 answers

Redux / ngrx/store architecture: why not dispatch actions from dumb components?

I'm building an Angular 2 ngrx/store application and trying to understand best practices. I love having an immutable state that changes only based on dispatched actions so that the app state is very clear and debug-able. I love one-way data flow…
David
  • 335
  • 4
  • 14
11
votes
1 answer

How many elements does it take for event delegation to become worthwhile?

Reading another Stack Overflow question about jQuery performance, I started thinking about the point when it becomes worth using event delegation rather than binding to elements individually. I was thinking mainly about jQuery, but I suppose it is…
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
11
votes
2 answers

How does jQuery.on() function?

I have not seen the source of this function, but I wonder, does it work like this: Selects element(s) by their selectors Delegates the provided event-handlers to them Runs a setInterval on that selector and constantly un-delegating, and then…
user1386320
9
votes
3 answers

What is the difference between target and currenttarget in flex?

Can any one please tell me the difference between target and currenttarget in flex?
8
votes
1 answer

Customising event delegates in the jQuery validation plug-in

I am currently setting up the jQuery validation plug-in for use in our project. By default, there are some events automatically set up for handling. I.e. focus in/out, key up events on all inputs fire validation. I want it to only fire when the…
Russell
  • 17,481
  • 23
  • 81
  • 125
8
votes
1 answer

Most efficient way to dynamically bind event handlers

Problem: I need to bind any number of event handlers to any number of elements (DOM nodes, window, document) at dynamically runtime and I need to be able to update event binding for dynamically created (or destroyed) nodes during the lifetime of my…
wvandaal
  • 4,265
  • 2
  • 16
  • 27
1
2 3
21 22