Last active
April 6, 2024 13:07
-
-
Save Machy8/1b0e3cd6c61f140a6b520269acdd645f to your computer and use it in GitHub Desktop.
jQuery .on() alternative in pure javascript (this handles events on dynamically added elements) π
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
/** | |
* @param {string} eventType | |
* @param {string} selector | |
* @param {function} callback | |
*/ | |
function on(eventType, selector, callback) { | |
document.body.addEventListener(eventType, function (event) { | |
if (event.target.matches(selector)) { | |
callback.call(event.target); | |
} | |
}); | |
} | |
var | |
selector = '.my-element', | |
eventType = 'click'; | |
on('click', '.my-element', function () { | |
alert('Muaha!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment