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.
Explanation
-
Lines 5-8: We use a CSS style for the
divelement with idelemto define width and overflow. -
Lines 10-12: We use a CSS style for the
divelement with idinsideto define width and background color. -
Line 20: We use
divelement with idelemand thechange()method binded with theonScroll()event. -
Line 21: We write another
divwith idinsideinside thediv. This creates a window with an outer width of 500px and inner width of 8000px, making it horizontally scrollable. -
Line 26: We use the
divelement with idelemto get thescrollLeftvalue. -
Line 27: We apply the
scrollLeftproperty on thedivelement. -
Line 28: We print the
scrollLeftvalue to the console.
Output
When we scroll left inside the div window, the value (pixels scrolled to the left) is displayed on the console.