HTML onscroll Event Attribute

Description

The onscroll HTML event attribute fires when an element's scrollbar is being scrolled. It can be used on any HTML element, but it is most commonly used on elements that have a fixed height, such as a div or iframe element with the overflow property set to auto or scroll.

When the user scrolls the element, the onscroll event is fired and the code specified in the attribute is executed. This code can be used to perform any number of tasks, such as:

  • Loading more data as the user scrolls down a page
  • Changing the appearance of the element as it is scrolled
  • Animating the contents of the element as it is scrolled

The following is a simple example of how to use the onscroll event attribute:

<div onscroll="myFunction()">
  </div>

The following JavaScript code will be executed whenever the user scrolls the div element:

function myFunction() {
  // Code to be executed when the div element is scrolled
}

The onscroll event attribute can be used to create a variety of dynamic and interactive web pages. For example, it can be used to create infinite scrolling pages, which load more content as the user scrolls down the page. It can also be used to create sticky navigation menus, which remain at the top of the page even as the user scrolls down.

Here are some additional examples of how the onscroll event attribute can be used:

  • Load more images in a gallery as the user scrolls down.
  • Play a video when the user scrolls to a certain section of a page.
  • Change the color of the navbar when the user scrolls down.
  • Display a back-to-top button when the user scrolls down a long page.

Syntax

<element onscroll="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onscroll event</title>
<style>
div {
width: 200px;
height: 150px;
border: 1px solid;
overflow: scroll;
}
</style>
</head>
<body>
<p>To demonstrate the onscroll event attribute, scroll the scroll bar of the following item:</p>
<div id="scrl" onscroll="scrl()">The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
</div>
<script>
function scrl () {
document.getElementById("scrl").style.backgroundColor="orange";
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onscroll Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 13th October 2023