Hi I have been looking on the internet trying to figure out the best practice for adding eventlistener to my websites and it generally comes down with two approaches as follow:
Adding an event listener to every elements (e.g. button) using a loop:
document.querySelectorAll('.some-button').forEach(item => {
item.addEventListener('click', event => {
//handle click
})
})
Or using event bubbling to use one listener only and check the e.target for each scenario:
body.addEventListener('click', event => {
if (event.target !== element1 && event.target !== element2) {
//return
}
//handle click
}
However, I was unable to find any article comparing the performance of these 2 approaches. From my limited understanding, whenever there is a ‘click’ javascript will loop through all the eventlisteners anyway (even though if you didn’t click on it) and for that reason I am taking the second approach (using one eventlistener) which seems to be the easier one to manage.
Appreciate if someone can provide further insights on the potential drawback of the second approach and if there will be any performance issue thanks.