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

Javascript click event on button with child markup

Trying to understand event delegation without the use of jQuery. I setup a event listener click on a container div. I want to limit the click to a button within the container. The problem is when the button contains markup, the target is the element…
user2433573
0
votes
2 answers

Delegating an event to the whole object

I have a jQuery plugin (which I've written) which has an option to match an optional child selector. Ie: If I have this markup:
Blah Numbers and Stuff
Echilon
  • 10,064
  • 33
  • 131
  • 217
0
votes
1 answer

Event Delegation: can someone explain me this JavaScript code?

I'm studying the event delegation on a book and I'm not sure I understood very well the concept. I know that it is used to "attach" an event to a parent element instead of attaching it to all the children. But I think I would not be able to use it…
lewis
  • 91
  • 2
  • 12
0
votes
2 answers

Stop applying a certain class to a parent of an event target

I am practising event delegation and I stumbled upon this. I have 4 paragraphs setting inside an article tag which sits in a div. I want to apply a .green class that changes background of each paragraph ONLY when I click on it. However the green…
Ahmed Magdy
  • 331
  • 1
  • 3
  • 9
0
votes
1 answer

Multiple events triggered when adding event handler to body element

I have some markers in a google map; I'd like add a listener to the body element, which will detect if the element clicked has a certain class and do certain actions if so. Now, everytime I click on target element, the event is triggered for all of…
George Katsanos
  • 13,524
  • 16
  • 62
  • 98
0
votes
0 answers

JS/jQuery call a function when an event fires

I have a conundrum and i don't know how to solve it. Let's say i have a jquery click event bellow (which is in Script A). $selector.on('click', function(e) { // 30 lines of code [it doens't matter what it does] }); Now i want to call…
lordZ3d
  • 540
  • 6
  • 20
0
votes
1 answer

jQuery: Turn off delegated events from original object, with namespace

I've attached a delegated event handler this way: $('#static-div').on('click.myNamespace', '.attach-to-this', someFunction); How do I then, later, reverse this action and remove all delegated events in that namespace? The static-div element is…
Matt
  • 23,363
  • 39
  • 111
  • 152
0
votes
2 answers

jQuery - Event delegation only targeting first newly-created element

I'm trying to create a simple reddit-like system where a user can add a post and then interact with the voting system (which pastes along with the form). While I have utilized event delegation, it only seems to be affecting my first newly-created…
0
votes
1 answer

To delegate typeahead on dynamically generated input

I have a html table which i am using to enter the inventory details .In this table I have a input box for product name on which I am binding typeahead event of bootstrap.But the problem is that for the first row input box which is already present on…
0
votes
1 answer

Observe Form Submission

In my application I need to submit forms via JavaScript. I know that I can do that with this code: [...document.querySelectorAll('form')].forEach(form => { form.addEventListener('submit', e => { //doing the processing here …
philipp
  • 15,947
  • 15
  • 61
  • 106
0
votes
1 answer

mouseup, click events and DOM manipulations

Stackers, I've got a curious case. There is a container element, that contains some other element with the class "clickable". The event listener to clickable 'click' is attached to the container, using delegation.
0
votes
1 answer

Why does event.stopPropagation() stop multiple matched elements in delegated events?

When using delegated events, all matching elements trigger the event as it bubbles up from the target. Based on https://learn.jquery.com/events/event-delegation/ and refering to HTML and JS below, clicking on div-four triggers click events on all…
Eric
  • 5,686
  • 2
  • 23
  • 36
0
votes
0 answers

JavaScript — Most performant no-op in mouse event listener?

Context I am building a Redux application, and would like click and mousemove event handlers to change depending on application state. To accomplish this, I am planning to attach a single click and single mousemove handler to the document. These…
A. Vidor
  • 2,502
  • 1
  • 16
  • 24
0
votes
0 answers

jQuery Event Delegation input type keyup blur

$('#item_code_wrapper').on('keyup blur', '#item_code', function(){ if( $(this).val() != ""){ $.ajax({ url : "../item/code/" + $(this).val(), success: function(data){ …
Rbex
  • 1,519
  • 6
  • 24
  • 50
0
votes
1 answer

Event delegation not working in X-tag

I can't get delegation to work with events. I'm trying to have a certain function fire when a button within the element is pressed. However, when I use the syntax provided ('tap:delegate(button)': function(){});) I get no response. Below is some…
babbitt
  • 103
  • 12