onscroll

The onscroll event in HTML is triggered when the content of an element is scrolled, allowing developers to execute scripts in response to changes in the scroll position.

onscroll event

The onscroll event handler in HTML is triggered when an element is scrolled, enabling developers to run specific actions or scripts based on the scroll position. This event is frequently used to implement features like lazy loading, infinite scrolling, or scroll-triggered animations.

Syntax

In HTML

index.html
<element onchange="myScript">

In JS

script.js
object.onscroll = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("scroll", myScript);

Example

::event-onscroll ::
index.html
<!DOCTYPE html>
<html>
<head>
<style>
div {
  border: 1px solid black;
  width: 200px;
  height: 100px;
  overflow: scroll;
}
</style>
</head>
<body>
<h1>The onscroll Event</h1>
<p>Try the scrollbar in div.</p>

<div onscroll="myFunction()">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'</div>

<p>Scrolled <span id="demo">0</span> times.</p>

<script>
let x = 0;
function myFunction() {
  document.getElementById("demo").innerHTML = x += 1;
}
</script>

</body>
</html>

In this example, the handleScroll function is called every time the user scrolls the page. It updates a fixed <div> with the current scroll position in pixels, allowing users to track how far they’ve scrolled. The body height is set to 2000 pixels to provide sufficient content for scrolling.

Values

Conclusion

The onscroll event in HTML is activated whenever an element is scrolled, enabling developers to trigger actions based on scroll position. It's commonly used for features like lazy loading, infinite scroll, and animations. The event can be handled directly in HTML, via JavaScript functions, or with addEventListener().