Smooth Page Scroll to Top with jQuery

February 21, 2012 jQuery 55 comments

If the web page has lots of content, its a good idea to provide visitors with an easy way to quickly scroll to the top of the page. In this tutorial, we will create smooth page scrolling effect for returning to the top of the page using jQuery.

We will create a button at a fixed position on the bottom right of the page, so that we once click it, it scrolls up with an nice animation rether than a page refresh or a straight jump to the top. We will make the button visible only if the page is scrolled down, instead of being always visible.

First, lets add the button link on the page, so that when it is clicked, we can scroll the page to the top.

<a href="#" class="scrollup">Scroll</a>

Now we can add CSS to the above button link:

.scrollup{
	width:40px;
	height:40px;
	opacity:0.3;
	position:fixed;
	bottom:50px;
	right:100px;
	display:none;
	text-indent:-9999px;
	background: url('icon_top.png') no-repeat;
}

As you can see, we have defined fixed position for the button which is 100px from right and 50px from the bottom. I have used the text-indent to hide the text and display the icon for the button. The disply:none makes the button invisible initially.

Now we want to make the button visible if the page is scrolled down. We can do that with jQuery scroll event.

$(window).scroll(function(){
		if ($(this).scrollTop() > 100) {
			$('.scrollup').fadeIn();
		} else {
			$('.scrollup').fadeOut();
		}
	});

The scrollTop gets the current vertical position of the scroll bar. If it is greater than 100px, it fades in the .scrollup button, otherwise fades out. So, when we scroll down the page more than 100px, the button should fade in, and if scroll up to the height of less than 100px it should fade out.

The next step is to to scrolling to the top smoothly, if the button is clicked. We can do use the click function for that.

$('.scrollup').click(function(){
	$("html, body").animate({ scrollTop: 0 }, 600);
	return false;
	});

The scrollTop:0 scrolls to the very top of the page, at 0px position, and the 600 represents the duration of animation in milliseconds. The Higher values indicate slower animations. You can also use ‘fast’, ‘slow’ or ‘normal’ instead of milliseconds.

Here is complete jQuery Code:

<script type="text/javascript">
	$(document).ready(function(){ 

		$(window).scroll(function(){
			if ($(this).scrollTop() > 100) {
				$('.scrollup').fadeIn();
			} else {
				$('.scrollup').fadeOut();
			}
		}); 

		$('.scrollup').click(function(){
			$("html, body").animate({ scrollTop: 0 }, 600);
			return false;
		});

	});
</script>

 

  • Chandrasekhar Uchiha

    How to add this to blogger??

  • Jennifer Wiss

    This is such an informative article and very clearly written. Every single thought and idea is direct to the point. Perfectly laid out. Thank you for taking your time sharing this to you readers.
    Plagiarism detection

  • buildakicker

    Great, simple usage. Thanks for the write up. I haven’t used the scrollTop()>100 jquery event before.

  • pjm

    I was not able to get this working on my site: http://www.philipmadeley.com is there a conflict with my other jq?

  • Pingback: 45 Highly Useful jQuery And JavaScript Tutorials

  • Jul

    I’ve followed a few of these tutorials, but this is the first one that really explains the code.  Now I feel like i could make some tweaks to it myself.  Thanks!

  • dealga

    thanks for this works a charm!

  • Be

    Hi!! it works perfectly, except that it’s always visible :( I played with the 100px value of the “.scrollTop() > 100)” part. but nothing changes :( please, help? thanks!!

    • Juan

      you can hide the button with the CSS .. display:none; …

  • http://www.facebook.com/thomas.heggstad Thomas Heggstad

    Well written article. Thanks! :)

  • ajit

    thanks for posting scrolltop…

  • Juan

    pretty solution… thanx

  • http://twitter.com/cmoreira Carlos Moreira

    Hello!
    This is a great example!
    Is it possible to make it stop once it reaches a point?
    I didn’t want it to be over the footer, for example, how can I achieve that? any thoughts?
    Thanks!

  • Gino

    Many thanks!!! :-)

  • wajih

    why this example is not working when i apply apply on different selector except html, body
    like hellow
    $(‘.scrollup’).click(function(){ $(“.secondp”).animate({ scrollTop: 0 }, 600); return false; });

  • Jake

    I spent most of the day looking for the best scroll to top, and yours was it! Need your help please. I tried placing the CSS into the Styles section of our header, and placed the other 2 (body link + jQuery) just above the body close tag. I’ve GOT IT working….but the prob is mine’s “invisible”? You can mouseover the lower portion of the page found here:

    http://imreview.com/%28866%29-467-3843

    then, do a page down (just to be sure), and then you won’t see the graphic. Instead if you put your cursor over the lower right corner (above and to the right of the “Contact Us”, there IS a hyperlink. Only it’s not visible. Can you please show me how I can fix this. I’m guessing (I could easily be wrong) it’s because of our black bg. Thanks in advance.

    • JC

      Still no answer

  • premiumwd

    thanks a lot really appreciate it

  • Umair Ali

    Great Work

  • pfosinger

    anybody who made this work: would you mind looking over a page for me? I’m missing something here…

    http://www.yarddogmusic.com/delete.htm

    • pfosinger

      followup:
      First issue:
      unless I add a bit to the link (style=”display: inline;”), I am not able to get the up arrow to display at all. Changing the display in that link to none hides it all the time. And if I delete the style=display code from the link, same problem: nothing is visible.
      Second issue: the animation is not working. It just flashes right up to the top, as a regular javascript would do. I have tried adjusting the milliseconds and have tried changing to Slow, as the tutorial suggests, but it has no effect at all.
      Anyone help?

      • http://gazpo.com Sami

        Have you tried to check if your jQuery code is not conflicting with the existing code?

  • jc

    If you go here: http://imreview.com/%28866%29-467-3843.htm it’s working by the icon (published to the images folder) is INVISIBLE). “Working” means you only find it if you’re hunting for it with your cursor and you know where it is > the cursor changes > you click it > it scrolls up. Can someone look at the code in our header and before body close tag and/or provide the solution? The icon is invisible, even when we try different opacities from 0.3 up to 1.0 default.

  • Nurlan

    Good job =)

  • sameera

    thank you!!!

  • M Sasan MH

    Great job, in chrome work perfect.
    but it’s not work perfectly in local(without web server) with IE 10. i don’t know why?

    • windson

      For me its not working in chrome. Any work aroudn? :(

      • M Sasan MH

        Try test it with virtual web server, like XAMPP

  • John

    Doesn’t work :( help me

  • Coni Design

    just need to add
    and it works perfectly! Thank you ;)

    • takovbg

      Yes, that’s true.
      After adding this in the – the example becomes full workable.

  • Jack

    Hello, I’m trying to add a simple scroll to top animate function using jquery but it jumps to the top rather than animate. I dowloaded jquery 1.8.3 and it says there’s a syntax error on line 1? I also don’t want the top button to fade in and out, I want it there permanently. Bear in mind I’m not a coder, but I’ve had a crack at it. Here’s my effort which doesn’t work:

    $(document).ready(function() {

    $(‘a[href=#top]‘).click(function(){

    $(“html, body”).animate({ scrollTop: 0 }, 600);

    return false;

    });

    });

    I only need this to finish my site and I feel like I’m close. Any advice to get this working would be much appreciated.

    Jack

  • 3D

    Easy to follow and implement. Thank you.

  • disquission

    Great article!
    Didn’t work the first time using the tutorial, initial debugging necessary, but I was able to figure it out after a few tweaks.

    Couple things not mentioned by the author:
    1) you need to add the source of the script, the script needs to be pulled from a library. In this case, it’s:

    You need to add this in the section.

    2) button link should be:
    Scroll
    This is to be placed at the bottom of the screen. Class is scroll up since in your CSS stylesheet, your class is defined as .scrollup:

    .scrollup{
    width:40px;
    height:40px;
    opacity:0.3;
    position:fixed;
    bottom:50px;
    right:100px;
    display:none;
    text-indent:-9999px;
    background: url(‘../images/icon_top.png’) no-repeat;
    }

    Hence, full html markup as per below:

    $(document).ready(function(){

    $(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
    $(‘.scrollup’).fadeIn();
    } else {
    $(‘.scrollup’).fadeOut();
    }
    });

    $(‘.scrollup’).click(function(){
    $(“html, body”).animate({ scrollTop: 0 }, 600);
    return false;
    });

    });

    Scroll

    CSS:
    .scrollup{
    width:40px;
    height:40px;
    /*opacity:0.3;*/
    position:fixed;
    bottom:50px;
    right:100px;
    display:none;
    text-indent:-9999px;
    background: url(‘../images/icon_top.png’) no-repeat;
    }

    • Guest

      inside the you need:
      Scroll

  • kristofer
  • DarkWolf

    Is best to use latest jquery (maybe from http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js ) or 1.** ? :)

  • Herman Strauss

    Can I please use the up icon on my site?

  • Alexander

    The scrolling back up code was pleasantly easy to add. Great job… Thanks.

  • sam anand

    It is not working properly in my site

  • Jawdat Anguiano

    Very helpful tutorial, as long as you mention to include the jQuery library hahaha (thank you “disquission”!!!!)

  • vikas

    image is coming on perticuler page. but jqery code for button hide and show on scroll bar is not working.

  • Lucas

    Congratulations for your code. It worked beautifully. =)

    I’ve tried lots of codes before and none of them worked.

    Thank you so much.

  • http://ruberMdesign.com/ ruben

    cool j query

  • J.J. Carlson

    Works like a charm. Thanks for the help!

  • royalspirit

    Oh I’ve been looking for this, this is exactly what I want, I saw this on one website and glad I found it. With fades and smooth scroll back to top. Wonderful!

  • http://www.facebook.com/shreshtt.bhatt Shreshtt Bhatt

    Thanks for writing this article… really helpful

  • kkriminal

    Thanks so much!

  • Vanilla

    from where i can get the images of top.png ?

  • Isabell

    how can this be realized without jquery???

  • ola

    parfait pour moi merci

  • vishal

    Thanks nice one…