Scroll to the top with jQuery!

This is a short tutorial on how to put a button on your web site that when clicked, will take the visitor to the top of the page in a smooth animation.

You can see how the button works by looking at the right side of my site. There should be a button there. If there isn’t a button there, scroll down a bit and it should appear. Try clicking on it :)

I’ve also made a simple demo page. You can download the demo here.

Step 1

Let’s start by adding jQuery to a page. You do that by pasting this code into the head tag of your html document.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

This will tell the browser to load jQuery from Googles server when your page is loaded.

Step 2

Add this html code to the bottom of your html, just before the body tag closes.

<a id="toTop" href="#">Go to Top</a>

This is the button/link that will take the user to the top when clicked.

Step 3

Now we’ll add some CSS for the button. It should also go into your head tag. We want the button to be located to the right and positioned in the vertical center of the page.

<style type="text/css">

#toTop {
 display: block;
 position: fixed;
 top: 50%;
 right: 0;
 padding: 10px;
 border: 2px solid red;
 background: white;

}
</style>

By using position: fixed; When the user scrolls, the button will always appear at the same place on the page.

Step 4

Now we’ll add script tags and initate jQuery.

<script>
 $(document).ready(function(){

// Javascript code will go here.

});
 </script>

The second line “$(document).ready(function()” will tell the browser to run the code inside these brackets when the page loads.

I always test if jQuery is working by typing “alert(“jQuery is working!”);” inside the document.ready function. Like this:

$(document).ready(function(){

// Javascript code will go here.
 alert("jQuery is working!");

});

If it works, when your refresh your page you should get an alert “jQuery is working!”, if not, you should check if you loaded jQuery correctly.

Step 5

We can finally add the javascript that will make the page automatically scroll up when the button is clicked.


$(document).ready(function()
 {

// Hide the toTop button when the page loads.
 $("#toTop").css("display", "none");

 // This function runs every time the user scrolls the page.
 $(window).scroll(function(){

// Check weather the user has scrolled down (if "scrollTop()"" is more than 0)
 if($(window).scrollTop() > 0){

// If it's more than or equal to 0, show the toTop button.
 console.log("is more");
 $("#toTop").fadeIn("slow");
 }
 else {
 // If it's less than 0 (at the top), hide the toTop button.
 console.log("is less");
 $("#toTop").fadeOut("slow");

}
 });

// When the user clicks the toTop button, we want the page to scroll to the top.
 $("#toTop").click(function(){

// Disable the default behaviour when a user clicks an empty anchor link.
 // (The page jumps to the top instead of // animating)
 event.preventDefault();

// Animate the scrolling motion.
 $("html, body").animate({
 scrollTop:0
 },"slow");

});

I hope I have commented the above code so you will understand what is happening. The demo html file also has comments in it to make it easier to understand. If something is not working properly or you think this is the best tutorial that’s ever been written, don’t hesitate to comment ;)

This entry was posted in Development. Bookmark the permalink.

8 Responses to Scroll to the top with jQuery!

  1. Matilda says:

    Love this script! But I got a problem.. I copy the codes and everything. But the jQuery doesn’t work. When I click on the link “back to top” it just jumps right back ut. The scroll/slide doesn’t happen, just a jump like u usually go to page. I tried the test with “alert(“jQuery is working!”);” and that work and showed up. What am I doing wrong?! Also tried the script to “Scrollto” and got the same problem there.. Totally a newbie at jquery.

    Hope u understand my crapy explanation!

  2. Hello,
    looks like there is an issue with Firefox (current version I’m using is 26.0)

    While this page (your tutorial text page)
    http://www.adriantomic.se/development/scroll-to-the-top-with-jquery/
    scrolls smoothly to the top

    the demo page
    http://www.adriantomic.se/scrolltotop

    doesn’t scroll, instead it bumps to top.

    Maybe you’d think to rewite/modify your tutorial to make it coherent with your article page ;-) and allow a more effective cross-browser compatibility

    Anyway, thank you for the guide,

    Robert

  3. Jesse says:

    Thanks for this. I couldn’t get it to work in FireFox but it works in Chrome. Also the script on this page did not work for me but I had to view the source in Firebug and used that script and it worked. Thanks again.

  4. Setup says:

    Having read this I thought it was really enlightening.
    I appreciate you spending some time and effort to put this content
    together. I once again find myself personally spending way too
    much time both reading and commenting. But so what, it was still worth it!

  5. susan says:

    Can all of this code be put into an external javascript folder? If so, is there any additional code needed in the html to call it?

    • Adrian says:

      Yes it is possible to put the code in a separate javascript file.

      1. Copy all the code below and paste it into a text file. Save it as scrolltotop.js in the same folder as your html file.
      $(document).ready(function()
      {

      // Hide the toTop button when the page loads.
      $("#toTop").css("display", "none");

      // This function runs every time the user scrolls the page.
      $(window).scroll(function(){

      // Check weather the user has scrolled down (if "scrollTop()"" is more than 0)
      if($(window).scrollTop() > 0){

      // If it's more than or equal to 0, show the toTop button.
      console.log("is more");
      $("#toTop").fadeIn("slow");
      }
      else {
      // If it's less than 0 (at the top), hide the toTop button.
      console.log("is less");
      $("#toTop").fadeOut("slow");

      }
      });

      // When the user clicks the toTop button, we want the page to scroll to the top.
      $("#toTop").click(function(){

      // Disable the default behaviour when a user clicks an empty anchor link.
      // (The page jumps to the top instead of // animating)
      event.preventDefault();

      // Animate the scrolling motion.
      $("html, body").animate({
      scrollTop:0
      },"slow");

      });

      2. In your header of your html document. Write the code below:

      3. Save and refresh view the html in a browser.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>