Skip to content

Instantly share code, notes, and snippets.

@duanemoody
Created February 9, 2025 01:05
Show Gist options
  • Save duanemoody/c3f10a0940416895876567e9c5963558 to your computer and use it in GitHub Desktop.
Save duanemoody/c3f10a0940416895876567e9c5963558 to your computer and use it in GitHub Desktop.
Vanilla implementation of jQuery .on() method
/**
* Delegation capable of detecting multiple events at the same time
* @param {string} events - space separated list of events
* @param {string} selector - CSS selector string
* @param {function} handler - callback function to call when event is captured
* @return {Object} - this object, for chaining
* @example
* containerElement.on("input", "input[type=tel]", function () {
* this.value = this.value.replace(/\D/g, "");
* });
*/
function on(events, selector, handler) {
events.split(' ').forEach(e => {
this.addEventListener(e, function(e) {
const t = e.target;
while (t && t !== this) {
t.matches(selector) && handler.call(t, e);
t = t.parentNode;
}
});
});
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment