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

can't select all elements with classList API

I'm having a problem selecting all the LI tags when converting jQuery code to HTML5 javascript code. I have applied the click event to the parent UL, and the click event is being applied to the correct clicked target LI. The class "selected" is also…
user1199178
  • 85
  • 1
  • 1
  • 6
0
votes
2 answers

remove dynamically populated
  • only works when the array contains odd number of items
  • live example of project: http://jsfiddle.net/k3buckuc/ enterItem = [] itemNumber = 0 // mark item as checked and add delete functionality function check() { $('#itemsListed').on('click', 'li', function() { …
    troychroi
    • 49
    • 1
    • 9
    0
    votes
    1 answer

    YUI panel buttons (click events) broken after adding tap event listeners

    Preface: Introducing YUI3 delegated on-tap events has seemed to broken all on-page default click events... buttons, input-field editing, radio button selection, etc. Everything worked fine before... all I did was include the event-tap module in a…
    csr19us
    • 105
    • 9
    0
    votes
    1 answer

    How to check which javascript loads and preforms quicker

    I have written in javascript two different ways to hover over links and have the background of the window change color, one using event delegation and one not. How do check which option is best performance wise (probably checking something in the…
    stecd
    • 1,681
    • 6
    • 19
    • 28
    0
    votes
    2 answers

    How to remove duplicate from addEventListener

    How to remove duplicate from addEventListener. I have site which uses ajax to populate different divs when user makes certain calls. I also have a Javascript function which grabs all the links and make an addEventListener so that I can filter the…
    0
    votes
    1 answer

    jquery Event Delegation

    I am attempting to rewrite a snippet of code using event delegation (in the hopes that it will stop conflict with another snippiet of js). but I've broken the code Original //to scale up on hover var current_h = null; var current_w =…
    Vynce82
    • 119
    • 3
    • 15
    0
    votes
    1 answer

    Jquery Function Hangs

    I am using a plugin called h5validate. I have found the only way to initiate this plugin is by clicking out of (bluring) the field i want to validate, so my logic is to setup a function which does this for me when i click (as it happens) a next…
    Edward
    • 1,806
    • 5
    • 26
    • 36
    0
    votes
    2 answers

    jQuery .on() not working with long dynamic content on Android and css()

    I'm trying to bind interactions to dynamically loaded links: HTML:
    My dynamic content will be here.
    JS: $(function(){ loadContent(); $('#content').css('height',400); …
    Yako
    • 3,405
    • 9
    • 41
    • 71
    0
    votes
    1 answer

    jQuery Geniuses - Init Plugins and Event Delegation

    Friends, Instead of manually init'ing every single instance: $("#MyChildId1").find("ul.sf-menu").superfish({ delay: 100, speed: 'fast' }); $("#MyChildId2").find("ul.sf-menu").superfish({ delay: 100, speed: 'fast'…
    0
    votes
    1 answer

    Javascript Event Delegation

    Im trying to rewrite the following function for event delegation: $("ul > li.closed").click(function (e) { if (e.target === this) { var li = $(this).closest('li'); li.find(' > ul').slideToggle('fast'); …
    sqe
    • 1,656
    • 4
    • 21
    • 38
    0
    votes
    1 answer

    Maintaining delegated event binding after removal of bound element(s)

    In a view, I have an unordered list to display elements that are bound to a user dropdown selection. These list elements are appended dynamically based on the server response. The HTML looks like:
    0
    votes
    1 answer

    event delegation in Hammer JS multi-tocuh events not working

    I'm trying to delegate the multi-touch gesture events in hammer.js with jQuery's .on(), but that doesn't seem to be working. This works: var main = $('.settings'); var hammerSwipeDown = Hammer(main, {prevent_default: true}).on('swipedown',…
    Django Johnson
    • 1,383
    • 3
    • 21
    • 40
    0
    votes
    1 answer

    Automatically initialize rich text editor on top of all textarea's, including ones that are loaded via ajax

    I'm developing an ajax heavy web app, and would like to have textarea's (with class="ui-richtext") automatically initialize TinyMCE. This is easy for textarea's that are loaded normally, but how about for content that is loaded AFTER the fact using…
    Nick P.
    • 275
    • 3
    • 9
    0
    votes
    2 answers

    touch events event delegation with jquery's .on()

    So I have this javascript code that listens for touch events on all elements in the document. document.addEventListener("touchstart", touchHandler, true); document.addEventListener("touchmove", touchHandler,…
    Django Johnson
    • 1,383
    • 3
    • 21
    • 40
    0
    votes
    2 answers

    jQuery load()/event delegation Issue

    Ok, I've just found out about event delegation, Click Issue: Dynamically Generated Links Not Triggering Click Function my issue here is as follows. The UL is loaded in via a jQuery load() call.
    llanato
    • 2,508
    • 6
    • 37
    • 59