What is the DOM scrollTop property?

Overview

In this shot, we will learn about the DOM scrollTop property, which can set or find the number of pixels vertically scrolled in an element.

The scrollTop property returns the number of scrolled pixels. We can also set the property by assigning a number in pixels. When assigning the pixels, the display of the content will be scrolled automatically.

Code

We will write a code to find how many pixels we have scrolled in the DIV element.

Console

Explanation

  • In lines 5-8, we have a CSS style for the div element with id elem that defines height and overflow.

  • In lines 10-12, we have a CSS style for the div element with id inside that defines height and background-color.

  • In line 20, we bind the Div element with id elem and the change() method with the onScroll() event.

  • In line 21, we write another div with id inside inside the DIV; this creates a window where the outer height is 100px and the inner height is 800px, which makes it scrollable.

  • In line 26, we get the Div element with id elem.

  • In line 27, we apply the scrollTop property on the Div element.

  • In line 28, we print the ScrollTop value on the console.

Output

When we scroll inside the DIV window, the value (pixels scrolled) is displayed on the console.

Free Resources