Skip to content

Instantly share code, notes, and snippets.

@Machy8
Last active April 6, 2024 13:07
Show Gist options
  • Save Machy8/1b0e3cd6c61f140a6b520269acdd645f to your computer and use it in GitHub Desktop.
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) 😎
/**
* @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