Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vanilla JS equivalent of jQuery's .live(): use event delegation to handle events whose target matches a selector, closest(): get nearest parent element matching selector
// get nearest parent element matching selector
var closest = (function() {
var el = HTMLElement.prototype;
var matches = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
return function closest(el, selector) {
return matches.call(el, selector) ? el : closest(el.parentElement, selector);
};
})();
// handle events whose target matches a selector
// works even on elements created after the event listener was added:
//
// delegateEvent('.todo .remove', 'click', function(removeBtn) {
// removeTodo(removeBtn.parentNode);
// }, '.todos'); /* elementScope is optional */
function delegateEvent(selector, eventType, handler, elementScope) {
(elementScope || document).addEventListener(eventType, function(event) {
var listeningTarget = closest(event.target, selector);
if (listeningTarget) {
handler.call(listeningTarget, event);
}
});
}
@allenhwkim

This comment has been minimized.

Copy link

commented May 14, 2017

Found this https://medium.com/@PitaJ/the-dom-is-getting-better-8d1a4eaf99e7

function delegate(element, event, descendentSelector, callback){
  element.addEventListener(event, function(e){
    var elem = e.target.closest(descendentSelector); 
    // returns null if no matching parentNode is found
    if(elem){ 
      callback(elem, e); 
    }
  }, false);
}

However, closet is not supported by IE. https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.