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

Neither .live(), .delegate() or .on() work for forms loaded dynamically to the page

I have a page with infinite scroll. The ajax functionality works fine for forms existing on the page when it initially loads, but doesn't work for forms loaded from the inifinite scroll ajax feature. I've searched for about 5 days trying to find a…
Mike
  • 65
  • 6
4
votes
1 answer

How to make my div with role="button" attribute clickable with the enter key

I have an app that needs to be fully navigable by keyboard. When I click on the header of a div (generated by a javascript/jquery function), an event listener is triggered. I was able to highlight the headers with tab by adding the attributes…
4
votes
3 answers

How can I delegate 'change' event on input element from body?

I know already about event delegation by jQuery. However, How can I do same thing with pure Javascript without jQuery. Although I attached change event on body or the top element(div), change event is not triggered when value of input element in…
4
votes
3 answers

what is behind of delegate() and live() method?

What is behind of delegate() and live() methods in jQuery that give them the ability of working for current and future elements within the page?
hd.
  • 17,596
  • 46
  • 115
  • 165
4
votes
2 answers

Reactjs: Event delegation similar to jQuery `on()`?

I am new to React.js. I created a list Component where items get added/removed frequently. Each item should have a click and/or hover events. I would like to do event delegation in similar way we do in jQuery using on(event, selector, data, handler)…
Vikram
  • 622
  • 1
  • 6
  • 18
4
votes
3 answers

Event Delegation, how to target a specific span inside a div

Given a bunch of divs like these:
Banana
Apple
Sergi
  • 1,192
  • 3
  • 19
  • 37
4
votes
1 answer

Event Delegation in jQuery - Which Method is Better?

In a bid to write better code and improve how I use jQuery, I've been doing some reading recently. One of the new tips I learnt is using event delegation with jQuery. While reading, I discovered two "supposed" different methods of addressing it.…
4
votes
1 answer

How to add click events for dynamically appended elements using jquery?

here i'm able to remove box100 and box200 when clicked but not able to remove box1-box5 after appending it to the list. How do I select the appended elements? https://jsfiddle.net/uhmgj8ky/4/ html
4
votes
1 answer

Binding a click event to content loaded via AJAX without making it delegated?

I have a situation where I am using the data attribute named data-command in many instances throughout a specific section of a site and instead of binding tons of separate click events I decided to just use the one and use a switch such…
Brett
  • 19,449
  • 54
  • 157
  • 290
4
votes
0 answers

Event delegation and Turbolinks: document or body?

When creating event handlers in a Rails/Turbolinks-enabled app, is it best to delegate to document.body or document? Is there an accepted convention? I've read that delegating to document is slightly less performant. However, it does allow you to…
4
votes
4 answers

My checkbox in a table is immediately unchecked

I have a table with checkboxes. When a checkbox is checked I catch the event with jQuery but this checkbox is immediately unchecked. The jsfiddle: http://jsfiddle.net/K4uDa …
Bronzato
  • 9,438
  • 29
  • 120
  • 212
4
votes
4 answers

Is there a rule of thumb for when to use event delegation vs event handling in JQuery?

I'm confused about when you should use event delegation as opposed to out-of-the-box JQuery event handling. I'm always tempted to use an event handler because it's so easy in JQuery: For example: $("button#submit").click(function () { …
fingerprint
  • 93
  • 1
  • 4
3
votes
6 answers

jQuery Event Delegation + Child Targeting Help

I display a bunch of posts from users on a page. I have the main parent div with the class name 'posts' and each post is outputted in a div with class name 'row' inside of it. So there's a whole lot of div.row's inside the div.posts. Each look like…
Seth
  • 582
  • 2
  • 5
  • 15
3
votes
5 answers

Jquery - Bind delegate to all "a" tags

i try to block the jq click() when you click on an link in a div. HTML JS $('#test').click(function() { alert('only when i click the div'); …
Peter
  • 11,413
  • 31
  • 100
  • 152
3
votes
4 answers

How do I register a Javascript event handler to an element that hasn't been added to the page yet

I'm trying to build a greasemonkey script which will dynamically create tables of data based on user interaction with... other dynamically created tables of data. My problem is that I'm having to make two passes every time I create a table: one to…
Randy
1 2
3
21 22
AA