What is the difference between window.onscroll and window.addEventListener

Viewed 2679

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?

2 Answers

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.

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

Related