References

Beginner-friendly references for web development, with live, editable examples.

The HTML onscroll event

Event All modern browsers Updated
Quick answer

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 inline onscroll attribute — it separates behavior from markup and allows multiple handlers.
  • Throttle or debounce scroll handlers, or use requestAnimationFrame, since they fire rapidly.
  • Prefer IntersectionObserver for "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?
It runs JavaScript when the element is scrolled. In JavaScript the event is named scroll.
Why is my scroll handler slow?
Scroll events fire very frequently. Throttle the work, or move it into a requestAnimationFrame callback.
What can I use instead of a scroll listener?
For detecting when elements enter the viewport, IntersectionObserver is more efficient than listening to scroll.
Should I use the onscroll attribute or addEventListener?
Prefer addEventListener('scroll', …) in JavaScript. The inline onscroll attribute works but mixes behavior into the markup and allows only one handler per element.