How to scroll contents of HTML body horizontally and vertically using JavaScript?

March 11, 2021

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


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


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 uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

What Is a Graph Database?MiscCSS align-items property examplesCSSHow to set up the local environment and workspace for Angular development?AngularCreate a simple bar chart and column chart using pure CSS gridCSSHow to send and receive query strings via links in Angular 9?AngularSolution for the error Commit failed – exit code 1 received in Desktop GithubMiscRelative Length Units in CSSCSSHow to convert a number rounding to a specified number of decimals in JavaScript?JavaScriptWordPress: How to print ACF array field values?WordPressDISTINCT ON: The confusing, unique and useful feature in PostgresPostgresOrder By and Group By in PostgresPostgresWhat is the difference between float and double?Misc