HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Execute a JavaScript when a <div> element is being scrolled
The onscroll event occurs when an element's scrollbar is being scrolled.
Event | |||||
---|---|---|---|---|---|
onscroll | Yes | Yes | Yes | Yes | Yes |
In HTML:
<element onscroll="myScript">
In JavaScript:
object.onscroll = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("scroll", myScript);
Bubbles: | No |
---|---|
Cancelable: | No |
Event type: | UiEvent if generated from a user interface, Event otherwise |
Supported 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 |
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 = "";
}
}
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";
}
}