Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

document.addEventListener VS element.addEventListener

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
})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading