Vanilla JavaScript Event Delegation

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));

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.matches('.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>

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){...} ).

Tags:

Javascript