onscroll
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
<element onchange="myScript">
In JS
object.onscroll = function(){myScript};
addEventListener()
function is used. In JavaScript, the
object.addEventListener("scroll", myScript);
Example
<!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()
.
onresize
The onresize event in HTML is triggered when the browser window or an element is resized, enabling developers to run scripts in response to the change.
onunload
The onunload event in HTML is triggered when a user leaves the page, enabling developers to run code right before the page is unloaded.