What is the DOM scrollLeft property?

Overview

In this shot, we will learn about the DOM scrollLeft property.

The scrollLeft property can set or find the number of pixels scrolled horizontally in an element or HTML page.

The scrollLeft property returns the pixels scrolled to the left or horizontally. We can also set scrollLeft by assigning a number in pixels. When we assign the pixels, the display of the content will automatically be scrolled to the left side horizontally.

Code

Let’s write a code to find how many pixels we scroll horizontally in div.

Console

Explanation

  • Lines 5-8: We use a CSS style for the div element with id elem to define width and overflow.

  • Lines 10-12: We use a CSS style for the div element with id inside to define width and background color.

  • Line 20: We use div element with id elem and the change() method binded with the onScroll() event.

  • Line 21: We write another div with id inside inside the div. This creates a window with an outer width of 500px and inner width of 8000px, making it horizontally scrollable.

  • Line 26: We use the div element with id elem to get the scrollLeft value.

  • Line 27: We apply the scrollLeft property on the div element.

  • Line 28: We print the scrollLeft value to the console.

Output

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

Free Resources