How to create Scroll to Top animation in jQuery With Example

Providing a good user experience is the primary concern of a web designer. You may have visited web pages with many scrollable pages and going back to top of such web pages is a tedious task for the users. You can add a scroll to top button to your web page, if you want to offer a good user experience.

In this post, we are going to discuss how to create a scroll to top animation in jQuery that will allow the users to easily scroll to top of the page with a single click.

I recommend you to go through the following tutorials before proceeding to this one.

You can use the following code to implement the scroll to top functionality with animation.

In this example, you can see how we created a scroll to top animation in jQuery. We have used jQuery scroll(), animate(), fadeIn() and fadeOut() function to animate the scroll to top animation technique.

First we add the following html link in the body that works as the scroll to top link in our web page.

You can attach an image to this link to make it attractive. We have added CSS classes to animate the scroll to top link. At first, we are not showing this link.

The following script shows how scroll to top animations works in jQuery.

jQuery scroll() method triggers when the window is scrolled . When the scroll event is fired or when we scroll down, we check if the current position of the scroll bar is greater than 100 then scroll to top is displayed else the link will be hidden. We animate this with jQuery fadeIn() and fadeOut() methods.

$("html, body").animate({scrollTop : 0},700); : Clicking the link will trigger the animate() method,which takes the parameters, scrollTop and the duration of this effect (700 milliSeconds).The scrollTop() method is used to get the current position of the scroll bar and the integer value 0 is the position where you reach on clicking the link. We set the duration of the effect as 700 milliSeconds. You can increase or decrease this value to vary the speed of the animation.

This is how we implement scroll to top animation in jQuery. Hope you all understood the technique. You can see it in action by visiting jQuery Scroll To Top Demo page.

That’s all for now and you will see more jQuery effects, animations and jQuery plugins related articles in the coming posts.

By admin

Leave a Reply

%d bloggers like this: