Last active
September 14, 2020 05:05
-
-
Save Daniel-Hug/abbded91dd55466e590b to your computer and use it in GitHub Desktop.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found this https://medium.com/@PitaJ/the-dom-is-getting-better-8d1a4eaf99e7
However,
closet
is not supported by IE. https://developer.mozilla.org/en-US/docs/Web/API/Element/closest