onscroll Event
Definition and Usage
The onscroll event occurs when the scrollbar of the element is scrolled.
Tip:Please use CSS overflow Style properties create a scrollbar for the element.
Instance
Example 1
Execute JavaScript when the <div> element is scrolled:
<div onscroll="myFunction()">
Example 2
Switch between class names at different scroll positions - When the user scrolls down 50 pixels from the top of the page, the class name "test" will be added to the element (and will be removed when scrolling back up).
window.onscroll = function() {myFunction()}; function myFunction() { if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {}} document.getElementById("myP").className = "test"; } document.getElementById("myP").className = ""; } }
Example 3
Slide in the element (add slideUp class) when the user scrolls down 350 pixels from the top of the page:
window.onscroll = function() {myFunction()}; function myFunction() { if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) { document.getElementById("myImg").className = "slideUp"; } }
Syntax
In HTML:
<element onscroll="myScript">
In JavaScript:
object.onscroll = function(){myScript};
In JavaScript, use the addEventListener() method:
object.addEventListener("scroll", myScript);
Note:Internet Explorer 8 or earlier versions do not support addEventListener() method.
Technical details
Bubbling: | Not supported |
---|---|
Cancelable: | Not supported |
Event type: | If generated from the user interfaceUiEvent. Otherwise Event. |
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 |
Browser Support
Events | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onscroll | Support | Support | Support | Support | Support |