How To Scroll To A Specific Position of A Webpage in JavaScript

Here you are going to learn how to scroll to a specific position in JavaScript. That means I am going to show you how easily you can Scroll to specific position of a webpage using JavaScript.

In many cases, it is seen that we need to add a button on the webpage to jump to a specific position. So, In this post, I am also going to create a button to jump to a specific position of a webpage.

Create a smooth scroll to top button in jQuery

Scroll to Specific Position in JavaScript

In order to achieve our goal our easiest way is to apply:

window.scrollTo( value-x, value-y );

Here value-x is the pixel value of the width, where you wanna jump or scroll to.

value-y is for the height of the window in terms of the pixel where you wanna jump or scroll to.

Let’s just understand it with an example.

<script type="text/javascript">
    function scrolling(){
   window.scrollTo(0,500);
    }
  </script>

You may also read,

Get the scroll position of a web page in the browser window using JavaScript

How to Scroll To a Specific Position Smoothly Using JavaScript

This is the script and now I am going to use it on a webpage.

<!DOCTYPE html>
<html>
<head>
  <title>Scroll to a specific div element onclick using JavaScript</title>
 <style type="text/css">
   
 body {
    width: 5000px;
    height: 5000px;
}
</style> 
</head>


<body>
  <button onclick="scrolling();">Click Me</button>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <p>Some Text</p>
  <script type="text/javascript">
    function scrolling(){
   window.scrollTo(0,500);
    }
  </script>

</body>
</html>

Now if you click on the button, it will scroll down the page to the 500 pixels of the webpage.

So you can use this to jump to a specific position of a webpage.

If you wanna scroll to the right side of your webpage just add some value to value-x.

window.scrollTo(500,0);

just like this one.

Leave a Reply

Your email address will not be published. Required fields are marked *