Handling Events for Many Elements | kirupa.com


#21

@TallGlassOfMike That still works. The approach described in this tutorial doesn’t work as well in that case, so maybe you’ll want to assign them individually like that.

Otherwise it would mean a more complicated filter. In using a single event listener, you need to be able to tell that what you clicked was what you wanted to be clicked. This was what if (e.target !== e.currentTarget) { ... } was doing - making sure that clicks that were made on #theDude (e.currentTarget) but not any of the one, two, three, four, or five buttons (e.target) were getting ignored. If the background of #theDude was clicked, for example, then e.target === e.currentTarget would be true.

If you have multiple buttons in different hierarchies, then the single handler would have to be applied to the common parent of those buttons. In a worst case scenario, that would be the body element. But then you would need to check e.target for basically every click made in the entire document to see if it’s one of your buttons. The check for this wouldn’t actually be too hard if you had a list of selectors targeting your buttons. It could be as simple as:

document.body.addEventListener('click', function (e) {
    if (e.target.matches('#parent1 .button, #parent2 .button, #parent3 .button')) {
        // do something with your clicked button
    }
});

But there is the downside of this check happening for every click in the common parent. If you’re ok with that (does one if check really matter that much?) then this could work for you. One event handler is a lot easier to manage than multiple event handlers and it means the dom can be changed and have .button elements added and removed and re-added without affecting the click handler at all.