Get and Set Scroll Position of an Element

In JavaScript, it is quite simple and easy to get and set the scroll position of an element of JS and especially when a user is building a user interface in the web browser. As when creating a user interface, we need to have an element that can be scrolled and for which it is required that you know its horizontal and vertical scrolling.

In this section, we will discuss how we can get and set the scroll position of an element and what the properties are used for doing so. With this, we will also discuss and implement some examples that will help us to get the concept better.

For getting and setting the scroll position of a JS element, there are following two properties of the element we need to use. These properties will enable to know the element's horizontal as well as vertical scrolling:

  1. scrollTop: The property of an element that returns the number of pixels permitted to the element's content to scroll vertically.
  2. scrollLeft: The property of an element that returns the number of pixels permitted to the element's content to scroll horizontally.

Other than this, the scrollTop and scrollLeft properties of the element are highly relative to the top left corner of the element, and as a result, by default, the value of the top left corner is (0, 0).

Let's see an implementation that will help us understand the use of both element's properties.

Implementation

Let's see two different example codes to know how we can get and set the scroll position of an element:

Setting the scroll position of an element using scrollRight property:

Below is the given code:

The output of the above code is shown below:

Get and Set Scroll Position of an Element

It is clear from the code that the scrollLeft property of the element gets and sets the element horizontally where on clicking on the button, the text gets scrolled in the horizontal direction. Similarly, the scrollRight property is used.

Example 2: Implementing scrollTop property of an element

We can have the same example code to get and set the element scroll position vertically:

The output of the above code is shown below:

Get and Set Scroll Position of an Element

It is clear from the code that the scrollTop property of the element gets and sets the element vertically on sliding, and the text gets scrolled in the vertical direction.

So, using both these element properties, we can know the element's position, and then we can set and get the scroll position of the element.