View video tutorial

HTML onscroll Attribute

HTML

The HTML onscroll attribute is an event handler used to specify a script that will run when an element's scrollbar is manipulated.

Definition and Usage


➔ The event is triggered by user or programmatic scrolling.

➔ This event can be used on most HTML elements, such as divs, paragraphs, sections, body elements, or window objects for the entire page.

➔ To use onscroll the element must have an active scrollbar, which can usually be achieved using the CSS overflow property (e.g. overflow: scroll; or overflow: auto;).

Syntax
//In HTML
<element onscroll="myFunction()">
//OR
<body onscroll="myFunction()">

//In javascript
document.getElementById("sample").onscroll=function() {myFunction();};
//OR
document.getElementById("sample").addEventListener("scroll", myFunction);
//OR 
window.addEventListener("scroll", (event) => {
    myFunction();
 });

Applies to

This attribute can be used on the following element.

Attribute Element
onscroll All visible elements

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML onscroll Attribute Example</title>
    <meta charset="utf-8" />
    <style>
        #myDIV {
            width: 350px;
            height: 150px;
            overflow: scroll;
        }
    </style>
</head>
<body>
    <h2>HTML onscroll Attribute Example</h2>
    <p>Try scrolling the scroll bar to the div element.</p>
    <p id="mypara"></p>
    <div id="myDIV" width="300" height="300" onscroll="myFunction()">
        <p>➔ The event is triggered by user or programmatic scrolling.</p>
        <p>➔ This event can be used on most HTML elements, such as divs, paragraphs, sections, body elements, or window
            objects for the entire page.</p>
        <p>➔ To use onscroll the element must have an active scrollbar, which can usually be achieved using the CSS
            overflow property (e.g. overflow: scroll; or overflow: auto;).</p>
    </div>
    <script>
        function myFunction() {
            document.querySelector("#mypara").innerHTML = "Scrolled";
        } 
    </script>
</body>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.