When I’m creating a web page, a confused happened to me, I noted that there are many elements waiting for clicking, so I want to ask:
which practice is better for the performance?
adding event listener for the document then check the class or id for the element I clicked:
document.addEventListener('click', e => {
let element = e.target.id;
if(element === navbarBtn) /* do something */;
if(element === goUpBtn) /* do something */;
if(element === darkModeSwitcherBtn) /* do something */;
})
OR
adding event listener for each element I will click:
navbarBtn.addEventListener('click', () => {
// doing something
})
goUpBtn.addEventListener('click', () => {
// doing something
})
darkModeSwitcherBtn.addEventListener('click', () => {
// doing something
})
>Solution :
It really depends on how you define better, as it’s very subjective.
One thing you definitely don’t want to do, is have your function run every single time anyone clicks something on your page. That’s very inefficient, and good code is efficient code.
It’s also much clearer from a readability standpoint that the functionality you want to apply to, say, a button, is attached to that button. It’ll be a nightmare later on if you have all your eventListeners attached to the document with a switch clause.
From a performance standpoint, meh. I’d imagine document is slightly faster, just due to the way the DOM works, with bubbling, etc., but the time saving (maybe 1ms), will instantly be used up on the element check.
Stick to using eventListeners on the element you’re working with, unless you absolutely need it to be on a parent element to utilise event delegation, in which case it should be as close as possible to the element that needs delegating to.
More info, and a handy diagram can be found on the w3 site.