Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onscroll — handling scrolling events

The onscroll attribute contains JavaScript executed when a scroll event is received. It lets an element react to scrolling, but does not itself create a scrollable area.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<div onscroll="/* JavaScript statements */">...</div>

onscroll is a global event-handler attribute for scroll. Its value is a JavaScript function body, not a URL. The attribute does not itself make anything scrollable; the example creates a scrollable area by constraining its height and setting overflow:auto.

Distinguish the HTML attribute from the JavaScript property element.onscroll, which accepts a function or null. Both forms use the same handler slot. On body and frameset elements, onscroll refers to the Window handler rather than an independent handler on that element.

Content Security Policy can block handlers written in attributes. In the example, the status paragraph starts empty. The script scrolls the box by assigning box.scrollHeight to box.scrollTop, then dispatches a synthetic scroll event with box.dispatchEvent(new Event('scroll')). The handler writes scroll: offset changed to the paragraph without any manual scrolling. The message makes the result checkable without assuming a particular number of events.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Element onscroll handler</title>
  <style>
    #box { block-size: 6rem; max-inline-size: 20rem; overflow: auto; border: 1px solid; }
    #content { block-size: 24rem; background: linear-gradient(#def, #468); }
  </style>
</head>
<body>
  <div id="box" role="region" aria-label="Scrollable sample" tabindex="0"
       onscroll="document.getElementById('result').textContent = event.type + (this.scrollTop > 0 ? ': offset changed' : ': at start')">
    <div id="content"></div>
  </div>
  <p id="result" role="status"></p>
  <script>
    const box = document.getElementById('box');
    box.scrollTop = box.scrollHeight;
    // Test the handler now rather than waiting for the browser's queued scroll event.
    box.dispatchEvent(new Event('scroll'));
  </script>
</body>
</html>

Result

scroll: offset changed

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources