I can't find the difference between doing:
window.onscroll = () => console.log("scroll")
and this:
window.addEventListener('scroll', () => console.log("scroll"))
except for browser patibility 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?
I can't find the difference between doing:
window.onscroll = () => console.log("scroll")
and this:
window.addEventListener('scroll', () => console.log("scroll"))
except for browser patibility 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?
Share Improve this question asked Mar 18, 2020 at 18:28 NourNour 5,4493 gold badges44 silver badges73 bronze badges 6- 3 Does this answer your question? addEventListener vs onclick – Henfs Commented Mar 18, 2020 at 18:29
- 1 "except for browser patibility which both seems to be unsupported in most IE versions" it's arrow functions that are unsupported, not event handlers – VLAZ Commented Mar 18, 2020 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 Commented Mar 18, 2020 at 18:41
-
@VLAZ if you check MDN documentation you will see that both ways have
Unknown patibility
under IE column developer.mozilla/en-US/docs/Web/API/Document/scroll_event developer.mozilla/en-US/docs/Web/API/Window/scroll – Nour Commented Mar 18, 2020 at 18:42 - Why do you mention browser frameworks, when your question is about vanilla JS event handling? – VLAZ Commented Mar 18, 2020 at 18:56
2 Answers
Reset to default 11The main differences is that there can only be one onscroll
. Any additional onscroll
s 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