Yogesh Chauhan's Blog

How to scroll contents of a an element vertically using JavaScript?

in JavaScript on March 10, 2021

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


el.scrollTop

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 height.

Example: scroll contents using JavaScript

You can make the scrolling smooth just using CSS or a cross-browser solution using jQuery.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Forcing the domain to serve securely using HTTPSMiscellaneousHow to check if the page is single post page in WordPress?WordPressGive buttons accessible namesUI/UXHow to Use SQL MAX() Function with Dates?SQL/MySQLHow to use @if and @else in SCSS?SCSSRIGHT JOIN in PostgresPostgresHow to convert an object from API to JSON array in Angular 9?AngularHow to send and receive query strings via links in Angular 9?AngularSolution to “NullInjectorError: No provider for module” in Angular 9AngularWhere is the PHP log file located on Mac OS?PHPEverything you need to know about ANY, SOME and ALL Operators in PostgresPostgresHow to select an element using its ID without the high specificity of the ID selector?CSS