9

I can't find the difference between doing:

window.onscroll = () => console.log("scroll")

and this:

window.addEventListener('scroll', () => console.log("scroll"))

except for browser compatibility which both seems to be unsupported in most IE versions !

is it just a syntax difference? it seems that it is straightforward to remove the handler using removeEventListener, but I'm assuming window.onscroll = null has similar effect.

am I missing anything?

Nour
  • 5,252
  • 3
  • 41
  • 66
  • 3
    Does this answer your question? [addEventListener vs onclick](https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick) – Azametzin Mar 18 '20 at 18:29
  • 1
    "*except for browser compatibility which both seems to be unsupported in most IE versions*" it's arrow functions that are unsupported, not event handlers – VLAZ Mar 18 '20 at 18:32
  • @Azametzin Partially yes, it is just annoying that most answers are very old to the fact you don't know if you still should care about them in recent modern frameowrks. I'm using React with a browser matrix that includes only modern browsers (I don't care about IE 9 or 11) So basically I need a short answer that is valid today not 6 years ago – Nour Mar 18 '20 at 18:41
  • @VLAZ if you check MDN documentation you will see that both ways have `Unknown compatibility` under IE column https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll – Nour Mar 18 '20 at 18:42
  • Why do you mention browser frameworks, when your question is about vanilla JS event handling? – VLAZ Mar 18 '20 at 18:56
  • @VLAZ I still have to use vanilla JS in React. I'm not aware of any way specific to React to handle scroll, right? – Nour Mar 18 '20 at 18:57

2 Answers2

10

The main differences is that there can only be one onscroll. Any additional onscrolls you add will override the first, whereas you can have as many .addEventListener('scroll', ()=>{}) as you want.

Austin Ezell
  • 753
  • 4
  • 12
3

There are several advantages to using addEventListener over onXXX. You can see my conversation with a zealot about this on SO here: How to interact my button with my function

For myself, I switched to using addEventListener every time when I started using Content-Security-Policy, which prohibits these inline functions. The issue is in script injection, where someone posts html elements with onXXX functions in an online chatroom, for instance.

The difference isn't huge, but it's better to only use addEventListener

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80