We know that we can use on page links (a tag) with id to navigate user on the same page. But that doesn’t always we need. What if we want to scroll down a bit higher or lower but not to a specific element?
Well, in that case, scrollTop DOM property comes handy.
We can use the scrollTop property to set the number of pixels on any element’s content and it should scroll vertically by that many pixels.
We can also use it to get the number of pixels any element has moved down vertically.
Very handy. Isn’t it?
Simply set the property like this syntax
el.scrollTop = number in pixels
Or get the property like this syntax
Things to remember
- 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 height.
You can make the scrolling smooth just using CSS or a cross-browser solution using jQuery.
DOM scroll scrollTop setInterval