Last Updated : Jan 1, 2023
You'll learn how to use the Element.scrollTop and Element.scrollLeft properties to get or set an element's scroll position.
The Element.scrollTop property gets the amount of pixels that an element's content is scrolled vertically.
The scrollTop value of an element is a measurement of how far the element's top is from its topmost visible content.
The scrollTop value is 0 when the content of an element does not generate a vertical scrollbar.
With a few exceptions, scrollTop can be any integer value:
- ScrollTop is 0 if the element cannot be scrolled (for example, if there is no overflow or if the element has the "non-scrollable" property).
- Negative values have no effect on scrollTop; instead, it resets itself to 0.
- If scrollTop is set to a value greater than the maximum possible for the element, it defaults to that value.
x-coord - The pixel in the upper left along the horizontal axis of the element you want to display.
y-coord - The pixel in the upper left along the vertical axis of the element you want to display.
- or -
The following parameters are contained in a dictionary:
top - Sets the number of pixels to scroll the window or element along the Y-axis.
left - Sets the number of pixels to scroll the window or element along the X-axis.
behavior - Specifies whether the scrolling should be smooth, instant, or left to the browser's discretion (auto, default).
- To begin, use selecting methods such as querySelector to select the element ().
- Second, use the scrollLeft and scrollTop attributes to get the element's scroll position.
- The Element.scrollTop gets the amount of pixels that an element’s content is scrolled vertically.
- The Element is a concept that has been around for a long scrolLeft gets or sets the number of pixels from an element's left edge that its content is scrolled.
- It's worth noting that the element's upper left corner is (0, 0). The scrollLeft and scrollTop coordinates are related to it..
So, utilizing both of these element attributes, we can determine the element's location, as well as set and retrieve the element's scroll position.