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

From a rendered list of flights, how does one access the specific flight-data which relates to the flight's booking-button that has been clicked?

From a fetched array of flight-data items I was able to created a table with each row displaying its specific flight-data alongside a button for booking the related flight. I want to add each button into an array so that I can use the array in order…
0
votes
1 answer

DOM Event Delegation isn't functional when using Jasny Bootstrap, how come?

My goal is to run some javascript after the change event for a set of inputs (some dynamically generated). I understand the necessity of DOM Event Delegation and how to implement it, but I'm running into some issues that I can't really explain other…
Thomas
  • 2,622
  • 1
  • 9
  • 16
0
votes
0 answers
0
votes
3 answers

Listen for events on certain element at window level - Javascript, no library

I want to listen for events on

elements at window or document level as there are too many such elements to attach an onclick event hander for each. This is what I've got: window.onload=function() { …

Francisc
  • 77,430
  • 63
  • 180
  • 276
0
votes
1 answer

Event delegation from target to all inner elements when HTML is dinamically appended?

I have this basic HTML that represents a button, I want to attach a click event, but this button is appendend dinamically to the container through a an ajax function, so because this is not present initialy in the DOM, I'm attaching the event to the…
silvered.dragon
  • 407
  • 1
  • 7
  • 19
0
votes
2 answers

Triggering a method from one class to an other using a button in Android SDK

I'm sorry if this is asked too much but I couldn't find something clear enough. I'm developing a little game engine for android. I've already implemented a gamepad class to control the touch screen. The game pad class draws an analog stick if…
0
votes
3 answers

Event delegation does not capture all inner elements

I am using event delegation on my project but for some reason it does not works as expected. It may seem like a duplicated question but searching for days I have not found the solution so it is not as clear, even in a course I am taking at UDEMY…
electronixG
  • 136
  • 1
  • 1
  • 18
0
votes
0 answers

Event delegation in React Native

Is it possible to create an event delegation in react native? We all know how it works in vanilla js, but I'm curious to know if it can be made in React Native
Jostar
  • 51
  • 3
0
votes
2 answers

Fire event on radio group after some time delay

I am searching for a solution to let an event fire on a radio group after some time delay. Specifically, I need to ask users a question and want to submit their input without having the users click a separate button. At the same time, it shall be…
0
votes
2 answers

Is it possible that if a span is a certain color do something?

I want to make sure that when the span element turns lime, an alert box shows up, however, I tried using both hasAttribute() and getAttribute() to try to make the if statement function properly, but both did not work for me, the error may be…
0
votes
2 answers

How can I add an onClick event listener to a table?

I am currently trying to add a feature where when I click the name of a user in the table it will display all of the posts made by that User however I am completely stumped. The url for the posts is https://jsonplaceholder.typicode.com/posts I…
0
votes
1 answer

how to change class on button click in javascript

I have this script but need to have the class to be changed to "go" or "stop". currently I can turn both to change to the class but it should change to one or the other Code var form =…
0
votes
2 answers

Trying to filter 4 different houses from an api

I'm trying to separate characters based on what house they belong to in the API (http://hp-api.herokuapp.com/api/characters) I have tried using .filter and .map, but have been unable to achieve that goal, I don't know if this is the right place to…
Vlskib
  • 3
  • 2
0
votes
0 answers

what is the connection of event propagation in event delegation?

const ul = document.querySelector("ul"); ul.addEventListener( "click", (event) => { console.log(event.target); }, true );
  • ITEM 1

  • ITEM 2

how is event propagation…
0
votes
2 answers

JavaScript Event Delegation without an actual event?

Hope my title is not too confusing. Please let me know if there is a better way to title my problem.I have jQuery function applying background-color to the odd rows in a table and on hover change the color to red. But if I edit the table dynamically…
Radi
  • 271
  • 6
  • 19