Skip to content

Instantly share code, notes, and snippets.

@Quaese
Last active December 11, 2022 16:07
Show Gist options
  • Save Quaese/9cd4b654f96b0bc9d0523a53f73bc2de to your computer and use it in GitHub Desktop.
Save Quaese/9cd4b654f96b0bc9d0523a53f73bc2de to your computer and use it in GitHub Desktop.
Live Event for Javascript (Vanilla JS, native JS)
/*
* Get nearest parent element matching selector.
*/
const closest = (function() {
const el = HTMLElement.prototype,
matches =
el.matches ||
el.webkitMatchesSelector ||
el.mozMatchesSelector ||
el.msMatchesSelector;
return function closest(el, selector) {
return matches.call(el, selector)
? el
: el.parentElement
? closest(el.parentElement, selector)
: null;
};
})();
/*
* Handle events whose target matches a selector.
* Works even on elements created after the event listener was added.
*
* live(
* 'li .time',
* 'click',
* function(removeBtn) {
* console.log(this, " was clicked!");
* },
* document.getElementById("element_id") // context is optional
* );
*/
const live = function(selector, eventType, callback, context) {
(context || document).addEventListener(eventType, function(event) {
const listener = closest(event.target, selector);
if (listener) {
callback.call(listener, event);
}
});
};
/* Example HTML:
*
* <ul id="element_id">
* <li class="list-item">
* <div class="time">Element for live event</div>
* <div class="title">
* No event - nothing happens
* </div>
* <div class="expand">
* No event - nothing happens
* </div>
* </li>
* </ul>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment