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
1 answer

Bind click event for parent using child element's id

I want to bind a click event on parent element using child element's id. I have this:
I want to do…
zeppelin
  • 451
  • 1
  • 4
  • 24
0
votes
2 answers

jquery undelegate click event after event has completed

I have a click event that animates in some AJAX content onto a page. Once this content has been revealed and a user clicks the same link that activated the process i now want to reverse the process and close the currently open fly out content. At…
RyanP13
  • 7,413
  • 27
  • 96
  • 166
0
votes
1 answer

Posting Comments to PHP Using Ajax

I'm having this comment form. this comment form works but not correctly whenever I post comment it works on 1 post and on another it refreshes the page and data is also not inserted all the post are fetch by while loop JS: < script type =…
user5405273
0
votes
2 answers

jQuery double event fire after post/get

ok i've wracked my brain and others to figure out why this is happening in IE and latest version of FF. It works in chrome. i am but a novice developer and recently started using jquery. so i dont even know if i'm going about this correctly. …
dtumbusch
  • 11
  • 2
0
votes
4 answers

Getting the target of the current bubbling phase when using event delegation

I have a div that contains some buttons and I want to attach an event listener to the div that listens for events that bubble up from the buttons inside of it. The problem I am running into is that the value of event.currentTarget does not appear…
Luke
  • 5,567
  • 4
  • 37
  • 66
0
votes
1 answer

jQuery event delegation and handlebars DOM elements

So I've had this problem for a few hours, and I've researched all the other answers and they all say that it has to do with assigning an event to a dom element that doesn't exists yet. The weird thing is: some of the problem dom elements work and…
matt lao
  • 331
  • 1
  • 2
  • 11
0
votes
3 answers

jQuery - Event delegation is occuring multiple times

I'm using event delegation in the pagination for my website. When you click the < or > buttons it moves the page up or down. The problem is that if you don't release the mouse button, in a split-second it will keep repeating the click handler. How…
mightyspaj3
  • 471
  • 1
  • 8
  • 22
0
votes
1 answer

High end javascript application and Event

I tried to have a title that match the context I want my answer for. I explain myself. After writting thousand of javascript lines of code (with or without jquery) I finally asked myself if I'm doing it wrong. Mainly thanks to jQuery adding…
h1fra
  • 324
  • 1
  • 3
  • 10
0
votes
1 answer

Event delegation from document or next static parent

Let's say we have the following HTML (with a button added after the page has loaded):
Now I'd like to know the exact difference between these two…
damian
  • 5,314
  • 5
  • 34
  • 63
0
votes
1 answer

Using JavaScript or JQuery to automatically check asp:checkbox when a button is pressed

I have a feature that allows the user to search the database for an item that matches the string they type in. For example, if they type in "Superman" it'll return whatever is in the database that is associated with Superman. Next to each item in…
0
votes
1 answer

Backbone passing a view an event and unbinding it from parent view

I was wondering if it is possible to pass a view en event, and then stop that event running again until another method has been run? This is my setup, Main View Method changeAdmin: function(e) { var element = $(e.currentTarget), userID…
Udders
  • 6,914
  • 24
  • 102
  • 194
0
votes
2 answers

Find what functionality is bound to a child through event delegation

if I delegate an event to an ancestor with something like $("#container").on("click", ".distant_child", function(){ //... } when I look in the developer tools in Chrome to see what click events are bound, I only see #container's events. Is…
1252748
  • 14,597
  • 32
  • 109
  • 229
0
votes
3 answers

MooTools Event Delegation using HTML5 data attributes

Is it possible to have event delegation using the HTML5 data attributes in MooTools? The HTML structure I have is: ​
not selectable
selectable
not selectable…
Anurag
  • 140,337
  • 36
  • 221
  • 257
0
votes
1 answer

How to measure the performance advantage arising due to Jquery event delegation?

My webpage has a grid which contains 500 rows and 30 columns. Each cell is either a dropdown or a textbox. As of now, we are attaching 'change' events to each of these elements individually. Recently, I learnt that JQuery event delegation using 'on'…
dinesh ygv
  • 1,840
  • 1
  • 14
  • 18
0
votes
1 answer

Referencing multiple elements in function using 'this' - JavaScript

Take this function: $(document).on('change', '#ele1, #ele2', function() { if (this.value == "") { $('.link').bind('click', false); } else { $('.link').unbind('click', false); } }); How would I reference the elements…
Edward
  • 1,806
  • 5
  • 26
  • 36