The HTML onscroll event
The HTML onscroll attribute runs JavaScript when an element or the document is scrolled. It is an inline handler for the scroll event; in modern code prefer addEventListener('scroll', …).
Overview
The onscroll event attribute runs JavaScript when the element is scrolled. In JavaScript the event itself is named scroll — drop the on prefix when you call addEventListener.
It is a scroll event, fired on a scrollable element or the document as the user scrolls. Scroll events can fire rapidly, so heavy work in the handler can hurt performance — throttle it, or prefer the more efficient IntersectionObserver where you can.
You can wire this up with the inline onscroll HTML attribute, but the modern, recommended approach is element.addEventListener('scroll', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element onscroll="handler()">…</element>
element.addEventListener('scroll', handler);
More Examples
Best practices
- Prefer
element.addEventListener('scroll', handler)over the inlineonscrollattribute — it separates behavior from markup and allows multiple handlers. - Throttle or debounce scroll handlers, or use
requestAnimationFrame, since they fire rapidly. - Prefer
IntersectionObserverfor "is it in view" checks rather than scroll math. - Use the CSS scroll-behavior for smooth scrolling instead of scripting it.
Frequently asked questions
What is the onscroll event?
scroll.Why is my scroll handler slow?
requestAnimationFrame callback.What can I use instead of a scroll listener?
IntersectionObserver is more efficient than listening to scroll.Should I use the onscroll attribute or addEventListener?
addEventListener('scroll', …) in JavaScript. The inline onscroll attribute works but mixes behavior into the markup and allows only one handler per element.