Execute a script when an element's scrollbar is being scrolled in HTML?

When an element's scrollbar is being scrolled, the onscroll event attribute triggers and executes a specified JavaScript function. This event fires when the user scrolls within an element that has scrollable content, making it useful for creating interactive scroll-based behaviors.

Syntax

Following is the syntax for the onscroll event attribute −

<element onscroll="functionName()">Content</element>

Alternatively, you can add the scroll event listener using JavaScript −

element.addEventListener('scroll', functionName);

How It Works

The onscroll event fires whenever the scrollTop or scrollLeft property of an element changes due to user interaction. This includes scrolling with mouse wheel, dragging the scrollbar, or using keyboard navigation within a scrollable container.

For an element to be scrollable, it must have the CSS property overflow set to scroll, auto, or hidden with content that exceeds the element's dimensions.

Example − Basic Scroll Event

Following example demonstrates how to execute a script when a div element is scrolled −

<!DOCTYPE html>
<html>
<head>
   <title>OnScroll Event Example</title>
   <style>
      #myDiv {
         width: 300px;
         height: 100px;
         border: 2px solid blue;
         overflow: scroll;
         padding: 10px;
         font-family: Arial, sans-serif;
      }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <p>Scroll inside the blue box to change text color:</p>
   <div id="myDiv" onscroll="changeColor()">
      This is sample content that extends beyond the visible area. 
      Keep scrolling to see more text and watch the color change.
      This is additional content to make scrolling possible.
      More text here to create scrollable content.
      Even more content for demonstration purposes.
   </div>
   <p id="status">Status: Not scrolled yet</p>
   
   <script>
      function changeColor() {
         var element = document.getElementById("myDiv");
         element.style.color = "red";
         document.getElementById("status").textContent = "Status: Element is being scrolled!";
      }
   </script>
</body>
</html>

When you scroll inside the blue box, the text color changes to red and the status message updates −

Scroll inside the blue box to change text color:
[Blue bordered scrollable box with black text that turns red when scrolled]
Status: Element is being scrolled!

Example − Tracking Scroll Position

Following example shows how to track and display the current scroll position −

<!DOCTYPE html>
<html>
<head>
   <title>Scroll Position Tracker</title>
   <style>
      #scrollContainer {
         width: 400px;
         height: 150px;
         border: 2px solid green;
         overflow: auto;
         padding: 15px;
         background-color: #f9f9f9;
      }
      #scrollInfo {
         margin-top: 10px;
         padding: 10px;
         background-color: #e8f4fd;
         border-radius: 5px;
      }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h3>Scroll Position Tracker</h3>
   <div id="scrollContainer" onscroll="trackScroll()">
      <h4>Sample Content</h4>
      <p>This is a long paragraph with extensive content that will require scrolling to view completely.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
      <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
      <p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
   </div>
   
   <div id="scrollInfo">
      <strong>Scroll Position:</strong> <span id="position">Top: 0, Left: 0</span>
   </div>
   
   <script>
      function trackScroll() {
         var container = document.getElementById("scrollContainer");
         var scrollTop = container.scrollTop;
         var scrollLeft = container.scrollLeft;
         document.getElementById("position").textContent = 
            "Top: " + scrollTop + ", Left: " + scrollLeft;
      }
   </script>
</body>
</html>

This example displays the real-time scroll position values as you scroll through the content −

Scroll Position Tracker
[Green bordered scrollable container with sample content]
Scroll Position: Top: 45, Left: 0 (values update as you scroll)

Example − Window Scroll Event

Following example demonstrates using onscroll on the entire window to create a scroll progress indicator −

<!DOCTYPE html>
<html>
<head>
   <title>Window Scroll Progress</title>
   <style>
      body { margin: 0; font-family: Arial, sans-serif; }
      #progressBar {
         position: fixed;
         top: 0;
         left: 0;
         width: 0%;
         height: 4px;
         background: linear-gradient(90deg, #ff6b6b, #4ecdc4);
         transition: width 0.1s ease;
         z-index: 1000;
      }
      .content {
         padding: 20px;
         line-height: 1.6;
      }
      .section {
         margin-bottom: 50px;
         padding: 20px;
         background-color: #f8f9fa;
         border-radius: 8px;
      }
   </style>
</head>
<body onscroll="updateProgress()">
   <div id="progressBar"></div>
   
   <div class="content">
      <h1>Scroll Progress Demo</h1>
      <p>Watch the progress bar at the top as you scroll down this page.</p>
      
      <div class="section">
         <h2>Section 1</h2>
         <p>This is the first section with sample content to demonstrate the scroll progress indicator.</p>
         <p>Keep scrolling to see the progress bar fill up as you move through the page content.</p>
      </div>
      
      <div class="section">
         <h2>Section 2</h2>
         <p>More content to create sufficient page height for scrolling demonstration.</p>
         <p>The progress bar calculates the scroll percentage and updates accordingly.</p>
      </div>
      
      <div class="section">
         <h2>Section 3</h2>
         <p>Final section of content. Notice how the progress bar approaches 100% as you reach the bottom.</p>
         <p>This demonstrates practical use of the onscroll event for user interface enhancements.</p>
      </div>
   </div>
   
   <script>
      function updateProgress() {
         var scrolled = window.pageYOffset;
         var maxScroll = document.documentElement.scrollHeight - window.innerHeight;
         var progress = (scrolled / maxScroll) * 100;
         document.getElementById("progressBar").style.width = progress + "%";
      }
   </script>
</body>
</html>

This creates a colorful progress bar at the top that fills as you scroll down the page, showing scroll completion percentage.

Common Use Cases

The onscroll event is commonly used for −

  • Infinite scrolling − Loading more content when user reaches bottom

  • Parallax effects − Moving background elements at different speeds

  • Sticky navigation − Showing/hiding navigation based on scroll position

  • Reading progress indicators − Showing how much of an article has been read

  • Scroll animations − Triggering animations when elements come into view

Browser Compatibility

The onscroll event is supported in all modern browsers including Chrome, Firefox, Safari, and Edge. For older Internet Explorer versions (IE8+), the event works reliably with proper testing recommended for legacy browser support.

Conclusion

The onscroll event attribute provides a simple way to execute JavaScript functions when users scroll within an element or the entire page. It enables creating interactive scroll-based features like progress indicators, infinite scrolling, and dynamic content loading, making web pages more engaging and user-friendly.

Updated on: 2026-03-16T21:38:53+05:30

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements