Vanilla JavaScript Event Delegation

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

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

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

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

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:

  • Event.target
  • Element.closest()
  • Delegated Events jQuery vs JavaScript

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật