Last active
December 11, 2022 16:07
-
-
Save Quaese/9cd4b654f96b0bc9d0523a53f73bc2de to your computer and use it in GitHub Desktop.
Live Event for Javascript (Vanilla JS, native JS)
This file contains 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. | |
*/ | |
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