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

Javascript dynamic content event delegation problem

Every time when a button is clicked, a checkmark will be displayed. If the clicked button is not active, the checkmark is removed. Also when the button is clicked the "load dynamic content"-button will be displayed. There is a problem when dynamic…
Sebu
  • 3
  • 3
0
votes
2 answers

How to use addEventListener on multiple input fields to invoke keyup event on them in JavaScript?

I have multiple input fields on which I want to apply onkeyup event on all of them with passing ID of textbox as a parameter. I want multiple keyup event because I want to handle some calculations on the basis of input ID. I tried but failed. Please…
0
votes
1 answer

How to use addEventListener on multiple input fields to invoke keyup event on them in JavaScript?

I have multiple input fields on which I want to apply onkeyup event on all of them with passing ID of textbox as a parameter. I want multiple keyup event because I want to handle some calculations on the basis of input ID. I tried but failed. Please…
0
votes
2 answers

Clicking outside of element with JavaScript e.target not working

I'm building a mega menu that has a close button on each menu that works great. However I need to write some JavaScript that says, 'if you click outside a mega menu when it's open, close it'. I've written a script below. It does detect when a user…
0
votes
0 answers

Why event delegation in Javascript is faster from normal child event?

Why number one code, is a normal child event listener code in js is slower than number 2 code, number two is event delegation in js. // #1 navLink.forEach(function (item) { item.addEventListener('click', function (e) { e.preventDefault(); const…
0
votes
1 answer

How does one add a product-item to a shopping-cart and how would one remove it from there while always (re)calculating the cart items' total price?

The following array features objects which are the product items. Clicking at the Add to cart button should render the related item into a table presentation via the mytable function as shown further below. var product = [ …
0
votes
2 answers

How could I apply a proper event handling or even event delegation to my example code?

I am trying to use the same function to change the color of three different divs, but it does not work. Please see below the code below: const hours=document.getElementById('hours'); const minutes=document.getElementById('minutes'); const…
0
votes
0 answers
0
votes
2 answers

Event delegation on click of an option, doesn't work on cloned element

My previous question (that was closed) -> Jquery - Cloning a div which includes input unordered lists. How to get the dropdown to work in the cloned row? I was referred to this answer: -> Event binding on dynamically created elements? I'm stuck at…
Daniel
  • 15
  • 4
0
votes
1 answer

How do I get the id of div wrapper in React when childnodes are the click event target?

I have a bottom navigation list of div elements which each contain a svg icon. When the user clicks on an icon I need the given id property to set the state of which the specific content is then rendered. I actually figured it out, but the problem…
andylib93
  • 133
  • 8
0
votes
1 answer

Event delegation not working on dynamic buttons

No matter what I try, the .onclick or addEventListener 'click' will not work on my dynamically created buttons and I can't figure out why. As I was looking for solutions, I came across Event Delegation and I looked through 3 different websites and…
sarchi-xo
  • 242
  • 2
  • 15
0
votes
1 answer

Attaching an event to CPagination change in Yii AFTER new page has been rendered

this is probably a newbie question so i hope it will be easy to answer!! i have been struggling for nearly a week with this.. please any help is much appreciated. I have a CListView and i am using the integrated cpagination. i have a javascript…
Soph
  • 2,895
  • 5
  • 37
  • 68
0
votes
0 answers

jQuery event Delegation Query

When I click on and element with a class of tool the alert box should show up but nothing happens, no errors in the console either. I'm pretty sure the issue I'm seeing is an event delegation issue, I just can't figure out where I'm going wrong. So…
llanato
  • 2,508
  • 6
  • 37
  • 59
0
votes
1 answer

Javascript Event Delegation / bubbling

I want to disable all links with the class "nolink" in the body section for an SPA router. To achieve this I used event delegation which does not work very well with nested elements. (Simplified code below). HTML:
user10962932
0
votes
0 answers

How to add eventlistener to dynamically created divs

How to add event delegation to dynamically created divs, to change property of the target div? I've tried several suggestions that I found for event delegation but none of them work. I think I'm making some mistakes but I don't know how to fix. I am…