Created
February 9, 2025 01:05
-
-
Save duanemoody/c3f10a0940416895876567e9c5963558 to your computer and use it in GitHub Desktop.
Vanilla implementation of jQuery .on() method
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
/** | |
* 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