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

How can I include the selected element in delegated jQuery's .on()?

I'm using jQuery's .on() with a selector to delegate to a filtered set of descendants, like this: selectedElement.on("click", "[data-click]", clickHandler); In this case, binding the clickHandler function to a click event on any descendant that has…
Robert
  • 6,660
  • 5
  • 39
  • 62
0
votes
2 answers

Content Added by jQuery.prepend Isn't Clickable (even when triggered by .on)

Thanks for any assistance. This site has been a great resource. My problem: When a menu is opened on a site I'm working on, I also prepend (to the body) a div overlay and give it a class that should allow it to be clickable to close the menu and…
leewaters
  • 15
  • 4
0
votes
2 answers

Applying class to dynamic element in jquery

Iam creating a dynamic input and applying a class to it, but its not working. My class: $(".numeric_input").keypress(function(e) { var a = []; var k = e.which; for (i = 48; i < 58; i++) a.push(i); if (!(a.indexOf(k)>=0)) …
vivek
  • 4,599
  • 3
  • 25
  • 37
0
votes
2 answers

Understanding Event Delegation Handling

I am trying to use event delegation for different forms on the same page. However, I am getting an interesting problem while trying to submit the forms. I tried 'click' on one form (intended for the submission button) knowing fully well that event…
user
  • 101
  • 1
  • 13
0
votes
2 answers

jQuery: single mouseenter/mouseleave handler

I need to track mouseenter / mouseleave events for all elements on the page. Intuitively written code for it was: $(window).on('mouseenter mouseleave', function(e) { console.log(e.target, e.type); // ... }); But it fires mouseleave events every…
Georgii Ivankin
  • 2,702
  • 2
  • 23
  • 35
0
votes
1 answer

jquery event delegate with on() to datatables table

I have jquery datatable with 4 pages. When I load the page the click event works fine. From the second page onwards click event doesn't work. I read the http://api.jquery.com/on/ link, but I am confused making it work.
user525146
  • 3,918
  • 14
  • 60
  • 103
0
votes
1 answer

Issue converting .live functions to .on

Updating some code base and having an issue I can't seem to conquer. Ive read the .on documentation and feel I have a decent enough understanding of it. The form is brought in via ajax.load when you sign in. No issue there. In a simple set up such…
Dirty Bird Design
  • 5,333
  • 13
  • 64
  • 121
0
votes
2 answers

jQuery event delegation in 1.7.2

Is there any way to delegate an event using jQuery that will correspond to all elements on the page that match the selector, other than delegating from $(document)? Since that's probably poorly worded, here's the rub: There used to be jQuery.live…
Thomas Jones
  • 4,892
  • 26
  • 34
0
votes
2 answers

Wire up different events and different selectors to same function

Let's say I have some code like this: $('#mywrapper') .on('click', 'button', myFunction) .on('change', 'input', myFunction) ; Is there a more efficient way to wire both event and selectors up to the same function?
Jason
  • 51,583
  • 38
  • 133
  • 185
0
votes
1 answer

jQuery event delegation with select elements?

While doing some sanity tests I noticed that the following change event binding works: $("body").on("change","input", function(){console.log(1)}) While the on event binding does not: $("body").on("change","select", function(){console.log(1)}) Is…
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
0
votes
2 answers

How to use the data from the row selected?

How can I collect the data on the row from the table that I select and use it in the result? Here is the javascript I am using to show the data entry screen, once the function has been called by selecting the row. Now I just need to design a form in…
Ben
  • 1,013
  • 4
  • 16
  • 34
0
votes
1 answer

Event Delegation with associated object for each DOM

I have a some DOM elements that are created dynamic with events and clousure. Something like this: var container = document.getElementById("container"); var objects = [{ name: "test" }, {name: "test2"}] for(var i = 0; i < objects.length;…
TryingToImprove
  • 7,047
  • 4
  • 30
  • 39
0
votes
2 answers

Javascript Event Delegtion -- Adding a timepicker to a popup form

I am attempting to create a timepicker inside of a popup form. I am struggling with event delegation -- I am capable of getting the timepicker to work outside of the form, but not inside. My current code, which does not have the timepicker popup: …
Paul
  • 375
  • 1
  • 5
  • 17
0
votes
2 answers

Problem using jquery UI droppable and livequery!

I have this code for some elements to be dropped var $tab_items = $("ul:first li",$tabs).droppable{ tolerance: 'touch' ,.... and it´s work ok, but the problem it´s when I load another button by ajax or by javascript, don´t work because the new…
Diego
0
votes
1 answer

Delegated focus event on textarea not fired on tabbing to the element

I have some textareas with some placeholder text loaded via AJAX. I want the text to disappear on focus, so I delegated the focus event on a class. The focus event is fired if I click the textarea and also fired on clicking/ tabbing to other input…