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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Solution for Xcode 11 Command PhaseScriptExecution failed with a nonzero exit code errorMiscellaneousHow to get category name using post id in WordPress?WordPressHow to create a CSS full page background image?CSSHow to convert a function component into a class in React?ReactCan Firewall and IDPS Stop DDoS Attack?MiscellaneousHow to make HTML form interactive and using CSS?CSSReview an intentionally vulnerable plugin in WordPressWordPressHow to add transparent text on top of an image using CSS?CSSHow to create and store JSON objects in localStorage using JavaScript?JavaScriptWhy it’s not a good idea to create Number objects in JavaScript?JavaScriptDebugging in WordPress Part 1: WP_DEBUGWordPressSolution for the error Commit failed – exit code 1 received in Desktop GithubMiscellaneous