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


amazon

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 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
What is Zdog?MiscellaneousWhat are Stored Procedures for SQL Server?SQL/MySQLCasting in PostgreSQLPostgresHow to create a for loop in SCSS (Sass)?SCSSHow to set opacity or transparency using CSS?CSSAttributes and Properties in JavaScript and HTMLHTMLA complete diagram with building blocks of an Angular applicationAngularFull and Partial ROLLUP in Postgresql with ExamplesPostgresHow to draw an SVG path on scroll using JavaScript?JavaScriptHow to use @each rule with key-value pair in SCSS?SCSSHow to Draw a Circle in HTML5 Using Canvas Tag?HTMLSELF JOIN in PostgresPostgres