Last active
July 17, 2022 11:26
-
-
Save donbrae/d78ee08d2ffdc2f7b8442155f9cf7fa1 to your computer and use it in GitHub Desktop.
JavaScript event delegation (vanilla JS vs jQuery)
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
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