HTML DOM Element scrollTop Property
- Previous Page scrollLeft
- Next Page scrollWidth
- Go to the Previous Level HTML DOM Elements Object
Definition and Usage
scrollTop
Property sets or returns the number of pixels the element content is vertically scrolled.
See also:
Instance
Example 1
Get the pixel number of the content of the scrolling 'myDIV':
const element = document.getElementById("myDIV"); let x = elmnt.scrollLeft; let y = elmnt.scrollTop;
Example 2
Scroll the content of 'myDIV' horizontally to 50 pixels and vertically to 10 pixels:
const element = document.getElementById("myDIV"); element.scrollLeft = 50; element.scrollTop = 10;
Example 3
Scroll the content of 'myDIV' horizontally by 50 pixels and vertically by 10 pixels:
const element = document.getElementById("myDIV"); element.scrollLeft += 50; element.scrollTop += 10;
Example 4
Scroll the <body> content horizontally by 30 pixels and vertically by 10 pixels:
const html = document.documentElement; html.scrollLeft += 30; html.scrollTop += 10;
Example 5
Switch between class names at different scroll positions - when the user scrolls down from the top of the page by 50 pixels, the class name "test" will be added to the element (and 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 6
When the user scrolls down from the top of the page by 350 pixels, slide in an element (add the slideUp class):
window.onscroll = function() {myFunction()}; function myFunction() { if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) { document.getElementById("myImg").className = "slideUp"; } }
Syntax
Return scrollTop property:
element.scrollTop
Set scrollTop property:
element.scrollTop = pixels
Attribute value
Value | Description |
---|---|
pixels |
The number of pixels the element's content is vertically scrolled.
|
Return value
Type | Description |
---|---|
Number | The number of pixels the element's content is vertically scrolled. |
Browser support
All browsers support element.scrollTop
:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support | Support |
- Previous Page scrollLeft
- Next Page scrollWidth
- Go to the Previous Level HTML DOM Elements Object