How to Animate Scrolling in jQuery

Anika Tabassum Era Feb 02, 2024
  1. Use the animate() Method to Scroll in jQuery
  2. Use the animate() Method With Time-Bound to Scroll Page in jQuery
How to Animate Scrolling in jQuery

jQuery is widely promoted for its easy syntax to accomplish complex ideas, while JavaScript ES6 is a tough competitor nowadays.

When we focus on scrolling a div or a webpage to a certain height, we notice several solutions. However, the jQuery animate() method explicitly accepts the instance of the body and html and scrolls as preference.

We will perform a basic vertical scroll in our example sets via the jQuery animate() method. In the latter example, we will examine an instance with a bounded time frame.

Use the animate() Method to Scroll in jQuery

In this regard, we will accept the instance of body and html elements. The convention is thus so that multiple browsers can run the function regardless of their constraints.

Next, we will initiate the animate() method along with the instance and set the specification scrollTop: "0". We can also set the scrollTop to any preference value.

In this case, the page will not route to the top; rather, it will climb to the distance between the whole page height and the scrollTop value.

Code Snippet:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<h4>TOP</h4>
<h4>TOP-20</h4>
<div id="pos" style="height: 600px;background:pink"></div><br>
<button onclick="press()">Go to Top</button>
<script>
function press(){
  $("html, body").animate({scrollTop: "20"});
}
</script>

Output:

Use animate Method to Scroll

Use the animate() Method With Time-Bound to Scroll Page in jQuery

This example includes a similar function as the previous one. But the addition here is that we can set the timing of the scroll without defining the setInterval function.

All we will do is add the preferable timing along with the scrollTop property. This will ease or ensure the speed value of the page scroll.

Code Snippet:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<h4>TOP</h4>
<div id="pos" style="height: 600px;background:powderblue"></div><br>
<button onclick="press()">Go to Top</button>
<script>
function press(){
  $("html, body").animate({scrollTop: "0"}, 3000);
}
</script>

Output:

Use animate Method with Time-Bound to Scroll Page

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - jQuery Scroll