HTML DOM Element scrollTop Property

Definition and Usage

scrollTop Property sets or returns the number of pixels the element content is vertically scrolled.

See also:

scrollLeft Property

CSS overflow Property

onscroll Event

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;

Try it yourself

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;

Try it yourself

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;

Try it yourself

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;

Try it yourself

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 = "";
  }
}

Try it yourself

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";
  }
}

Try it yourself

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.

  • If the number is negative, set the number to 0.
  • If the element cannot be scrolled, set this number to 0.
  • If the number is greater than the allowed maximum value, set the number to the maximum value.

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