20

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();
}
12
  • 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 Commented May 7, 2014 at 3:32
  • 1
    Would suggest you post that as an answer. Commented May 7, 2014 at 3:33
  • 1
    Relevant: developer.mozilla.org/en-US/docs/Web/API/Element.matches Commented May 7, 2014 at 3: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. Commented May 7, 2014 at 3:35
  • 1
    I guess the jQuery implementation is pretty good :)
    – Ian Clark
    Commented May 29, 2014 at 21:51

4 Answers 4

20

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>

4
  • 1
    document.querySelector is not going to fly if DOM is not loaded yet. This is not quite delegation.
    – mlt
    Commented Jan 30, 2020 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. Commented Jan 30, 2020 at 21:15
  • My bad.. indeed OP's case would work. I should have elaborated as I was looking for solution compatible with Turbolinks. 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
    Commented Jan 30, 2020 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
    Commented Jan 15, 2023 at 5: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));
3
  • You ought to check first for the standard unprefixed version.
    – gilly3
    Commented Nov 20, 2015 at 16:12
  • @gilly3 I should also calculate it once rather then every time. I'll update
    – Ian Clark
    Commented Nov 20, 2015 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). Commented Feb 9, 2018 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){...} ).

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:

Not the answer you're looking for? Browse other questions tagged or ask your own question.