How to Scroll To a Specific Position Smoothly Using JavaScript

By Saruque Ahamed Mollick

In this tutorial post, I am going to show you an easy way to scroll to a specific position of a webpage smoothly using JavaScript. So this will be very much useful for those who want to know how to scroll to a specific position smoothly in JavaScript.

In my previous post, I have shown you How To Scroll To A Specific Position of A Webpage in JavaScript.

Now I am going to add an extra feature that is, smooth scrolling.

Scroll to a specific position smoothly in JavaScript

This is how you  cam Scroll To A Specific Position Smoothly in JavaScript

 window.scrollTo({
    options
});

Here options are of 3 properties.

  1. top ( height in pixels to be scrolled )
  2. left ( width in pixels to be scrolled )
  3. behavior ( smooth, instant and auto )

We are going to learn smooth scrolling so we will use smooth.

 window.scrollTo({
    top: 2000,
    behavior: "smooth"
});

This will scroll your page to the 2000 pixel smoothly. ( you can use top and left both properties at the same time if you wish, depending on your needs )



Create a smooth scroll to top button in jQuery

Here is an example of smooth auto scrolling,

<!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({
    top: 3000,
    behavior: "smooth"
});
    }
  </script>

</body>
</html>

Special note:

You if you want to scroll from the current position you can use this below code:

function scrolling(){ 
window.scrollBy({ 
top: 3000, 
behavior: "smooth" 
}); 
}

As you are going to scroll from the current position so the top and left value can be positive or negative.

Real Time Chat Application PHP With File Transfer System AJAX

Leave a Reply

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