W3cubDocs

/Web APIs

Element: scroll event

The scroll event fires when an element has been scrolled. To detect when scrolling has completed, see the Element: scrollend event.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

js

addEventListener("scroll", (event) => {});

onscroll = (event) => {};

Event type

A generic Event.

Examples

The following examples show how to use the scroll event with an event listener and with the onscroll event handler property. The setTimeout() method is used to throttle the event handler because scroll events can fire at a high rate. For additional examples that use requestAnimationFrame(), see the Document: scroll event page.

Using scroll with an event listener

The following example shows how to use the scroll event to detect when the user is scrolling inside an element:

html

<div
  id="scroll-box"
  style="overflow: scroll; height: 100px; width: 100px; float: left;">
  <p style="height: 200px; width: 200px;">Scroll me!</p>
</div>
<p style="text-align: center;" id="output">Waiting on scroll events...</p>

js

const element = document.querySelector("div#scroll-box");
const output = document.querySelector("p#output");

element.addEventListener("scroll", (event) => {
  output.innerHTML = "Scroll event fired!";
  setTimeout(() => {
    output.innerHTML = "Waiting on scroll events...";
  }, 1000);
});

Using onscroll event handler property

The following example shows how to use the onscroll event handler property to detect when the user is scrolling:

html

<div
  id="scroll-box"
  style="overflow: scroll; height: 100px; width: 100px; float: left;">
  <p style="height: 200px; width: 200px;">Scroll me!</p>
</div>
<p id="output" style="text-align: center;">Waiting on scroll events...</p>

js

const element = document.querySelector("div#scroll-box");
const output = document.querySelector("p#output");

element.onscroll = (event) => {
  output.innerHTML = "Element scroll event fired!";
  setTimeout(() => {
    output.innerHTML = "Waiting on scroll events...";
  }, 1000);
};

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
scroll_event 1 12 6 9 ≤12.1 1.3 4.4 18 6 ≤12.1 1 1.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/scroll_event