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

Programmatically fired events not working with event delegation

Would really appreciate if anyone can help me figure out why I am unable to fire events programmatically when using event delegation in MooTools (from the Element.Delegation class). There is a parent
that has a change listener on some child…
Anurag
  • 140,337
  • 36
  • 221
  • 257
7
votes
2 answers

Closure event delegation - event listener on DOM parent that covers children/descendants of a given class

In jQuery, you can do the following: $('#j_unoffered').on('click', '.icon_del', function () {... This puts one handler on the element j_unoffered that fires if any descendant element with class icon_del is clicked. It applies, furthermore, to any…
Nick
  • 5,995
  • 12
  • 54
  • 78
7
votes
3 answers

Jquery on event is not binding for non existing elements

Ok here the jsfiddle example http://jsfiddle.net/HTjCT/1/ As you can see you when you hover it is not firing mouseover event how can i solve this problem ? i am using Jquery 1.9
Click Me
$(function () { …
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
6
votes
2 answers

Issue regarding live event

I was just reading http://api.jquery.com/event.stopPropagation/ Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events I was a bit confused with…
Rocky Singh
  • 15,128
  • 29
  • 99
  • 146
6
votes
1 answer

jQuery event delegation is not working on jQuery UI datepicker

I'm trying to stop a particular click event from bubbling to document-root, which in result closes one of my popup. I need to stop bubbling of the event and body or html are my only options to intercept and stop it. The date-picker popup is…
6
votes
4 answers

Add click event to element inserted by javascript

If I click on the first "Edit" I get a console.log('click happend') But if I add a one of these boxes via javascript (click on "Add box") and then the Edit click from this new box does not work. I know it's because the javascript run when the…
caramba
  • 21,963
  • 19
  • 86
  • 127
6
votes
3 answers

Remove jQuery delegated event handler on specific object

I've attached delegated event handlers to a number of elements on the page using a single selector. As the events are triggered for individual elements, I'd like to turn off only that element's event handler based on some conditional logic. That…
Matt
  • 23,363
  • 39
  • 111
  • 152
5
votes
2 answers

jquery event delegation variable scope with consecutive calls

With event delegation in jQuery 1.6, you can respond to events that have bubbled up to a common parent. A sample implementation is like this: (function($){ $.fn.myeventhandler = function () { return this.delegate('a.next, a.prev', 'click…
MyStream
  • 2,533
  • 1
  • 16
  • 33
5
votes
1 answer

Catch the load event from iframes, using jQuery delegation

I want to catch the load even of any iframe which is appended on the document at some point after loading the page. I tried using on("load", "iframe", fn), but that doesn't seem to do it: function addIframe() { $("
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
5
votes
1 answer

addEventListener vs onclick with regards to event delegation

I’m learning about how events work, mainly event capturing and bubbling in addEventListener. This article was great for the overall understanding. Capturing and bubbling define the order in which events in parent elements occur. As far as I…
5
votes
1 answer

Event delegation and window versus window.document

I want to do event delegation and capture all events happening on a DOM object by an event handler bound to the entire document. Is there any difference between binding the events to window as in: window.addEventListener(event, function(e){ var…
sawa
  • 165,429
  • 45
  • 277
  • 381
5
votes
2 answers

Using jQuery .on() for all events

Is it considered bad practice to use jQuery's .on() event handler for every event? Previously, my code contained script like this: $('#cartButton').click(function(){ openCart(); }); However I've recently started using InstantClick (a pjax…
Dan Johnson
  • 1,480
  • 17
  • 36
5
votes
1 answer

Get container with on() in jQuery

I have a button inside a div to hide that div and I want to pass the div to the handler. Here is my current code: $('#hidden-div').on('click', '#hide-btn', { element : $('#hidden-div') }, hideElement); Is there any way to avoid reselecting the…
Lim H.
  • 9,870
  • 9
  • 48
  • 74
5
votes
4 answers

Performance overhead of event listeners on CSS classes used in JQuery code

If my markup looks like this:
fingerprint
  • 93
  • 1
  • 4
5
votes
5 answers

Which JavaScript libraries have event delegation?

I'd like to try out a new JavaScript library. Having used (and loved) jQuery 1.3's "Live" events, I'd prefer the next library I try to have event delegation built in to the event system. Wikipedia's JS Library Comparison falls down on the job…
Nosredna
  • 83,000
  • 15
  • 95
  • 122
1
2
3
21 22