We just saw an example of scrolling the content of an element. We can apply the same technique here.
To scroll the HTML body content vertically we can use scrollTop DOM property. You can read more about it in this post.
To scroll the HTML body content vertically we can use scrollLeft DOM property. Let’s look at the details.
We can use the scrollLeft property to set the number of pixels on any element’s content and it should scroll horizontally by that many pixels.
We can also use it to get the number of pixels any element has moved down horizontally.
Simply set the property like this syntax
el.scrollLeft = number in pixels
Or get the property like this syntax
el.scrollLeft
Things to remember
- Try not to set the number of pixels in negative. It doesn’t work like margin or padding. JavaScript will convert the negative number to a zero.
- If you try to scroll any element that is not scrollable, then again JS will set the number to a zero.
- If you set the scrolling number in pixel greater than the box itself, then it will be set to the maximum box width.
Example: scroll body contents using JavaScript
horizontally scroll scrollLeft scrollTop vertically