Skip to main content

Alex Carpenter

Event delegation gotcha follow-up

Yesterday I wrote about an event delegation gotcha that I ran into while building a few small JS libraries. I ran the post by Chris Ferdinandi and he pointed out I could make use of a different method called closest() instead of matches() as seen below.

document.addEventListener('click', event => {
// If event doesn't match our toggle selector return
if (!'.accordion-toggle')) return
if (!'.accordion-toggle')) return
// Run toggle code
}, false)

Depending on the browsers you are looking to support, matches() offers a little better support than closest(). So using the one line css trick might be an option for you if you are counting bytes.