Yogesh Chauhan's Blog

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

in JavaScript on 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


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


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
The basics of @import rule in SCSS (Sass)SCSSHigher Order Functions in JavaScript with ExamplesJavaScriptHow to remove the Gutenberg Block Library CSS from WordPress?WordPressHow to check if checkbox is checked or not using JavaScript?JavaScriptDifference between :where and :is in CSSCSSArray.from() Method in JavaScriptJavaScriptPHP arrays for US states’ full names and abbreviationsPHPCheck whether a variable exists and not empty in PHPPHPHow to add a Bar Chart in Angular App?AngularSome EASY-to-Understand CSS media query examplesCSSFor In Loop in Swift for BeginnersSwiftKilling A Project Part 4: What Would Be Your Top 3 Priorities For Planning The Cancellation?Miscellaneous