Skip to content

Instantly share code, notes, and snippets.

@donbrae
Last active July 17, 2022 11:26
Show Gist options
  • Save donbrae/d78ee08d2ffdc2f7b8442155f9cf7fa1 to your computer and use it in GitHub Desktop.
Save donbrae/d78ee08d2ffdc2f7b8442155f9cf7fa1 to your computer and use it in GitHub Desktop.
JavaScript event delegation (vanilla JS vs jQuery)
document.addEventListener('click', function (e) {
for (let target = e.target; target && target != this; target = target.parentNode) {
if (target.matches('.foo')) {
// ⋯
e.preventDefault();
break;
} else if (target.matches('.bar')) {
// ⋯
e.preventDefault();
}
}
}, false);
// jQuery equivalent
$(document).on('click', '.foo', function (e) { // ⋯
e.preventDefault();
});
$(document).on('click', '.bar', function (e) { // ⋯
e.preventDefault();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment