19

What is the best way ( fastest / proper ) fashion to do event delegation in vanilla js?

For example if I had this in jQuery:

$('#main').on('click', '.focused', function(){
    settingsPanel();
});

How can I translate that to vanilla js? Perhaps with .addEventListener()

The way I can think of doing this is:

document.getElementById('main').addEventListener('click', dothis);
function dothis(){
    // now in jQuery
    $(this).children().each(function(){
         if($(this).is('.focused') settingsPanel();
    }); 
 }

But that seems inefficient especially if #main has many children.

Is this the proper way to do it then?

document.getElementById('main').addEventListener('click', doThis);
function doThis(event){
    if($(event.target).is('.focused') || $(event.target).parents().is('.focused') settingsPanel();
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
MrGuru
  • 325
  • 5
  • 15
  • 4
    Start with the `event.target`, see if it matches the selector, and if so, invoke the function. Then iterate up through its ancestors and do the same until you get to the `this` element. You can use `node.matchesSelector()` to do the test, though in some browsers it's implemented with a browser-specific flag, so you'd either need to wrap it in a function, or put the flag method on `Element.prototype.matchesSelector` – cookie monster May 07 '14 at 03:32
  • 1
    Would suggest you post that as an answer. – Evan Trimboli May 07 '14 at 03:33
  • @EvanTrimboli: I don't like posting answers. I'll let someone else get the rep. Feel free if you'd like. – cookie monster May 07 '14 at 03:34
  • @cookiemonster why would I find the child element and then go up? – MrGuru May 07 '14 at 03:34
  • 1
    Relevant: https://developer.mozilla.org/en-US/docs/Web/API/Element.matches – Felix Kling May 07 '14 at 03:34
  • 1
    @MrGuru: Because that's how event delegation works. You have to see if any node in the element hierarchy matches the selector, starting with the element where the event originates and stopping at the element you bound the handler to. – Felix Kling May 07 '14 at 03:35
  • @MrGuru: If you're implementing event delegation, then you know that the `event.target` was the element clicked, so that's the first one to test. But it could be that the event bubbled up from the `event.target` and encountered a different element that matches, so you'd usually want to include that. That's basically what jQuery does. Like `
    click me
    `. The `event.target` will be the `span`, so we iterate up to find the `.focused`.
    – cookie monster May 07 '14 at 03:36
  • @cookiemonster I can use jQuery everywhere except listening for the event. Is the way I put in my question the proper way to do it? – MrGuru May 07 '14 at 04:23
  • @MrGuru: The handler should be invoked once for each ancestor that matches the selector, and the ancestors should stop before the `this` element. So maybe `$(event.target).parentsUntil(this, ".focused").each(settingsPanel)` – cookie monster May 07 '14 at 05:11
  • 1
    I guess the jQuery implementation is pretty good :) – Ian Clark May 29 '14 at 21:51
  • 1
    [Relevant David Walsh article](https://davidwalsh.name/event-delegate) – Blazemonger Nov 20 '15 at 15:49
  • Closely related: [Attach event to dynamic elements in javascript](/q/34896106/4642212). – Sebastian Simon Jan 15 '23 at 04:07

4 Answers4

18

Rather than mutating the built-in prototypes (which leads to fragile code and can often break things), just check if the clicked element has a .closest element which matches the selector you want. If it does, call the function you want to invoke. For example, to translate

$('#main').on('click', '.focused', function(){
    settingsPanel();
});

out of jQuery, use:

document.querySelector('#main').addEventListener('click', (e) => {
  if (e.target.closest('#main .focused')) {
    settingsPanel();
  }
});

Unless the inner selector may also exist as a parent element (which is probably pretty unusual), it's sufficient to pass the inner selector alone to .closest (eg, .closest('.focused')).

When using this sort of pattern, to keep things compact, I often put the main part of the code below an early return, eg:

document.querySelector('#main').addEventListener('click', (e) => {
  if (!e.target.closest('.focused')) {
    return;
  }
  // code of settingsPanel here, if it isn't too long
});

Live demo:

document.querySelector('#outer').addEventListener('click', (e) => {
  if (!e.target.closest('#inner')) {
    return;
  }
  console.log('vanilla');
});

$('#outer').on('click', '#inner', () => {
  console.log('jQuery');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="outer">
  <div id="inner">
    inner
    <div id="nested">
      nested
    </div>
  </div>
</div>
Community
  • 1
  • 1
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    [`document.querySelector` is not going to fly](https://stackoverflow.com/q/20495960/673826) if DOM is not loaded yet. This is not quite delegation. – mlt Jan 30 '20 at 19:59
  • 1
    Sure it is - just like OP's jQuery code of `$('#main').on('click', '.focused', function(){` is delegating clicks inside `#main` to `#main`'s click listener, my code is doing the same thing. This is the technique to use if `#main`'s children are dynamic (like if `#main` is a todo list container). If `#main` itself may not exist, that's a different situation, and would of course require delegating the events to an outer parent. – CertainPerformance Jan 30 '20 at 21:15
  • My bad.. indeed OP's case would work. I should have elaborated as I was looking for solution compatible with [Turbolinks](https://github.com/turbolinks/turbolinks#observing-navigation-events). It removes everything but document and window. I ended up using only `.matches` with complete selector and without `querySelector` on document like in your last example. – mlt Jan 30 '20 at 21:49
  • 1
    The second snippet uses a simple `target.matches()`, which isn't the same as `.closest()` in that it would require the event to fire on that element directly and not on one of its descendants. I guess this isn't intended. – Kaiido Jan 15 '23 at 05:52
15

I've come up with a simple solution which seems to work rather well (legacy IE support notwithstanding). Here we extend the EventTarget's prototype to provide a delegateEventListener method which works using the following syntax:

EventTarget.delegateEventListener(string event, string toFind, function fn)

I've created a fairly complex fiddle to demonstrate it in action, where we delegate all events for the green elements. Stopping propagation continues to work and you can access what should be the event.currentTarget through this (as with jQuery).

Here is the solution in full:

(function(document, EventTarget) {
  var elementProto = window.Element.prototype,
      matchesFn = elementProto.matches;

  /* Check various vendor-prefixed versions of Element.matches */
  if(!matchesFn) {
    ['webkit', 'ms', 'moz'].some(function(prefix) {
      var prefixedFn = prefix + 'MatchesSelector';
      if(elementProto.hasOwnProperty(prefixedFn)) {
        matchesFn = elementProto[prefixedFn];
        return true;
      }
    });
  }

  /* Traverse DOM from event target up to parent, searching for selector */
  function passedThrough(event, selector, stopAt) {
    var currentNode = event.target;

    while(true) {
      if(matchesFn.call(currentNode, selector)) {
        return currentNode;
      }
      else if(currentNode != stopAt && currentNode != document.body) {
        currentNode = currentNode.parentNode;
      }
      else {
        return false;
      }
    }
  }

  /* Extend the EventTarget prototype to add a delegateEventListener() event */
  EventTarget.prototype.delegateEventListener = function(eName, toFind, fn) {
    this.addEventListener(eName, function(event) {
      var found = passedThrough(event, toFind, event.currentTarget);

      if(found) {
        // Execute the callback with the context set to the found element
        // jQuery goes way further, it even has it's own event object
        fn.call(found, event);
      }
    });
  };

}(window.document, window.EventTarget || window.Element));
Ian Clark
  • 9,237
  • 4
  • 32
  • 49
  • You ought to check first for the standard unprefixed version. – gilly3 Nov 20 '15 at 16:12
  • @gilly3 I should also calculate it once rather then every time. I'll update – Ian Clark Nov 20 '15 at 17:41
  • I would recommend using `window.Node` instead of `window.Element`. The document itself inherits from `Node`, getting the functionality to work in IE (which doesn't have `EventTarget`). – Kevin Drost Feb 09 '18 at 12:11
1

I have a similar solution to achieve event delegation. It makes use of the Array-functions slice, reverse, filter and forEach.

  • slice converts the NodeList from the query into an array, which must be done before it is allowed to reverse the list.
  • reverse inverts the array (making the final traversion start as close to the event-target as possible.
  • filter checks which elements contain event.target.
  • forEach calls the provided handler for each element from the filtered result as long as the handler does not return false.

The function returns the created delegate function, which makes it possible to remove the listener later. Note that the native event.stopPropagation() does not stop the traversing through validElements, because the bubbling phase has already traversed up to the delegating element.

function delegateEventListener(element, eventType, childSelector, handler) {
    function delegate(event){
        var bubble;
        var validElements=[].slice.call(this.querySelectorAll(childSelector)).reverse().filter(function(matchedElement){
            return matchedElement.contains(event.target);
        });
        validElements.forEach(function(validElement){
            if(bubble===undefined||bubble!==false)bubble=handler.call(validElement,event);
        });
    }
    element.addEventListener(eventType,delegate);
    return delegate;
}

Although it is not recommended to extend native prototypes, this function can be added to the prototype for EventTarget (or Node in IE). When doing so, replace element with this within the function and remove the corresponding parameter ( EventTarget.prototype.delegateEventListener = function(eventType, childSelector, handler){...} ).

Kevin Drost
  • 383
  • 4
  • 7
0

Delegated events

Event delegation is used when in need to execute a function when existent or dynamic elements (added to the DOM in the future) receive an Event.
The strategy is to assign to event listener to a known static parent and follow this rules:

  • use evt.target.closest(".dynamic") to get the desired dynamic child
  • use evt.currentTarget to get the #staticParent parent delegator
  • use evt.target to get the exact clicked Element (WARNING! This might also be a descendant element, not necessarily the .dynamic one)

Snippet sample:

document.querySelector("#staticParent").addEventListener("click", (evt) => {

  const elChild = evt.target.closest(".dynamic");

  if ( !elChild ) return; // do nothing.

  console.log("Do something with elChild Element here");

});

Full example with dynamic elements:

// DOM utility functions:

const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// Delegated events
el("#staticParent").addEventListener("click", (evt) => {

  const elDelegator = evt.currentTarget;
  const elChild = evt.target.closest(".dynamicChild");
  const elTarget = evt.target;

  console.clear();
  console.log(`Clicked:
    currentTarget: ${elDelegator.tagName}
    target.closest: ${elChild?.tagName}
    target: ${elTarget.tagName}`)

  if (!elChild) return; // Do nothing.

  // Else, .dynamicChild is clicked! Do something:
  console.log("Yey! .dynamicChild is clicked!")
});

// Insert child element dynamically
setTimeout(() => {
  el("#staticParent").append(elNew("article", {
    className: "dynamicChild",
    innerHTML: `Click here!!! I'm added dynamically! <span>Some child icon</span>`
  }))
}, 1500);
#staticParent {
  border: 1px solid #aaa;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.dynamicChild {
  background: #eee;
  padding: 1rem;
}

.dynamicChild span {
  background: gold;
  padding: 0.5rem;
}
<section id="staticParent">Click here or...</section>

Direct events

Alternatively, you could attach a click handler directly on the child - upon creation:

// DOM utility functions:

const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Create new comment with Direct events:
const newComment = (text) => elNew("article", {
  className: "dynamicChild",
  title: "Click me!",
  textContent: text,
  onclick() {
    console.log(`Clicked: ${this.textContent}`);
  },
});

// 
el("#add").addEventListener("click", () => {
  el("#staticParent").append(newComment(Date.now()))
});
#staticParent {
  border: 1px solid #aaa;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.dynamicChild {
  background: #eee;
  padding: 0.5rem;
}
<section id="staticParent"></section>
<button type="button" id="add">Add new</button>

Resources:

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313