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

Observing events for elements with a certain class or that element's children using event delegation

I have a page with elements similar to this:
Some text
The code is similar to this: $('things').observe(click,…
Sam
  • 14,642
  • 6
  • 27
  • 39
0
votes
3 answers

Event delegation in jQuery, how to do it?

In JavaScript i used to use event delegation like this : someDiv.addEventListener('click', function(evt){ if(evt.target.id == "#someChild"){ // Do something.. } else if(evt.target.id == "#anotherChild"){ // Do something else.. …
Rafael Adel
  • 7,673
  • 25
  • 77
  • 118
0
votes
1 answer

Ignore child elements using jQuery event delegation

I am using the on method to delegate a click event to injected divs. These injected divs will have child divs as well that are positioned outside of their parent div. I am looking to ignore the click event on the child divs but can't seem to figure…
Randy Gonzalez
  • 445
  • 5
  • 17
0
votes
1 answer

Event delegation, why is this not working, selecting target by id

Edit #2: The problem does not exist anymore. It was some kind of scoping problem. But now it's working.I am really sorry for the inconvenience. In some part of my script there's an event delegation and specifying target by id. But when i run it.…
Rafael Adel
  • 7,673
  • 25
  • 77
  • 118
0
votes
2 answers

how to ignore checkbox inside td

I am using jQuery's event delegation to add a click event to table rows. I also have a checkbox in the first td of the row. When I click anywhere in the row everything works as expected. However, I don't want the event to work when I click in the…
JsusSalv
  • 517
  • 1
  • 8
  • 22
0
votes
2 answers

Correct syntax for defining an event delegator

Normally you write a handler for a button click like this: $(document).ready(function() { $("button").click(function() { doSomething(); }); }); But in the case of an event delegator, to respond to an event with a function such as…
0
votes
1 answer

delegate events on self

I am writing an event delegating plugin that takes 4 params: context = String selector child element = String selector event = String fn = Function to call The plugin must delegate events to the child element if the parent is present in the DOM so…
mkoryak
  • 57,086
  • 61
  • 201
  • 257
-1
votes
3 answers

Remove Item from shopping cart does not work

REMOVE button does not work. Even in console when i click the button nothing appears in the console. Can anyone spot the problem? I feel like something is wrong with the classes, not sure though. This JS for shopping cart. Its not the whole js code…
-1
votes
2 answers

how to store click event in local storage

How to store click event in a local storage to use it after page refresh. const container = document.querySelector('.filter ul'); container.addEventListener('click',(event) =>{ const closest = event.target.closest('.accordion-header'); if…
rocky
  • 23
  • 6
-1
votes
3 answers

Declare a let variable without assigning a value in Javascript, why that is?

I found this in Javascript.info : enter link description here. Well it's a event delegation demonstration : a 9-cells table, when we click one of cells, the cell (event.target) changes its color into red and the cell we clicked just before will…
-1
votes
1 answer

Event Delegation - event trigger with wrong class

I'm trying to create a slider with html- vanilla javascript. I'm able to open a modal, show a wide slider image and small images (thumbnails). Everything looks fine but when I click the thumbnails (which have "small_image" class) they trigger…
Teoman Tıngır
  • 2,766
  • 2
  • 21
  • 41
-1
votes
1 answer

$(event.target) not detecting any inner element

I have an element that when clicked, shows an inner text (which is initially set to display: none). I want to add a span inside that inner text to close that text, but $(event.target) is not working in this case and I'm not sure why. It's also worth…
Sergi
  • 1,192
  • 3
  • 19
  • 37
-1
votes
2 answers

How to use event delegation when using clipboardjs?

Clipboardjs is awesome, but I wonder how to use event delegation when using it. Here is my code: 0
hanzichi
  • 609
  • 2
  • 12
  • 22
-1
votes
2 answers

What is "this" inside the event .on('click', 'class', function () {})

I try to have access to the row i clicked to add or remove a class, but it seems like i misinterpreted the value of this. Isn't it supose to be the DOM where the event go called (in this case, the
  • )? Here is my code:…
  • MacGruber
    • 162
    • 2
    • 13
    -1
    votes
    1 answer

    Event Delegation -- JQuery Skips Click

    I am adding content [buttons & tables] to my 'container' uses the load method. However, dynamic content requires delegation and I believe my code for this is wrong and I am somehow confusing parents/children. When I load my page, my 'table' is…
    Christopher
    • 790
    • 12
    • 30
    1 2 3
    21
    22