Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jquery
javascript
html
css

What is animate scrollTop?

Shahpar Khan

Animate scrollTop is a handy feature that can be implemented to give an added functionality to users.

Let’s assume that you are developing a website that hosts blogs, a Blogspot. Usually, article pages have details on the top about the article, and a lengthy article that flows to the very bottom of the webpage. Instead of having users scroll back to the top, wouldn’t it be nice to give them a feature that allows them to, with the press of a button, navigate back to the top of the webpage?

For this very reason, our friend JQuery provides us with a helpful feature called .scrollTop().

When .scrollTop() is invoked, it will return the page’s pixels to the top position.

Below is a snippet about Spiderman. Scroll to the bottom and click on the Get Position button; an alert will tell you the top position.

The .scrollTop()function can be coupled with another function called .animate(). As the name suggests, .animate() is used to back any navigation on the web page with smooth animations.

To move to the top position, use the .scrollTop() method and give it as an input to .animate(). Below is the above example, but it’s been modified a bit to incorporate the animation.

function scrollTop() { 
            $("html, body").animate({ scrollTop: "0" }, 5000); 
        }

We have a function called scrollTop(), which is the scrollTop feature’s backbone. First, we used the Jquery selector ("html, body") to ensure that our code is compatible with different browsers. Next, we used the .animate() method, which takes a dictionary of CSS properties and values as the first parameter. An integer represents the animation duration in milliseconds as the second parameter. We specified where .animate() should scroll to by giving a value of “0” to the scrollTop property as the first argument and, to indicate the duration of the scrolling animation, giving a value of 5000 as the second argument.

Note: The duration of animation (second argument) is given in milliseconds. Therefore, the value of 5000 means that the animation will last 5 seconds.

RELATED TAGS

jquery
javascript
html
css

CONTRIBUTOR

Shahpar Khan
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring