onscroll Event
Example
Call a function when a <div> element is being scrolled:
<div onscroll="myFunction()">
Try it Yourself »
Description
The onscroll event occurs when an element's scrollbar is being scrolled.
Tip: use the CSS overflow style property to create a scrollbar for an element.
Browser Support
Event | |||||
---|---|---|---|---|---|
onscroll | Yes | Yes | Yes | Yes | Yes |
Syntax
In JavaScript, using the addEventListener() method:
object.addEventListener("scroll", myScript);
Try it Yourself »
Technical Details
Bubbles: | No |
---|---|
Cancelable: | No |
Event type: | UiEvent if generated from a user interface, Event otherwise |
HTML tags: | <address>, <blockquote>, <body>, <caption>, <center>, <dd>, <dir>, <div>, <dl>, <dt>, <fieldset>, <form>, <h1> to <h6>, <html>, <li>, <menu>, <object>, <ol>, <p>, <pre>, <select>, <tbody>, <textarea>, <tfoot>, <thead>, <ul> |
DOM Version: | Level 2 Events |
More Examples
Example
Toggle between class names on different scroll positions - When the user scrolls down 50 pixels from the top of the page, the class name "test" will be added to an element (and removed when scrolled up again).
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Try it Yourself »
Example
Slide in an element when the user has scrolled down 350 pixels from the top of the page (add the slideUp class):
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
document.getElementById("myImg").className = "slideUp";
}
}
Try it Yourself »
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.