Using jQuery to add a dynamic “Back To Top” floating button with smooth scroll

Jul 18, 2013
CSS HTML
148 Shares
By

Ever read a really long blog post or article and then had to scroll all the way up to the top of the screen to get to the menu? It can be a little frustrating. It’s easy to fix, you can have a fixed menu or as you’ll see here you can provide a quick and stylish way to get back to the top.

Getting Started

HTML wise all we need to do is add a “back to top” link at the bottom of the blog post

<a href="#" class="back-to-top">Back to Top</a>
scroll-to-top-no-css

We then need to style and position it. Here I’m setting its position to fixed and moving it to the bottom right side of the screen. I’ve also given it a semi-transparent background and finally hidden it. To make it stand out a little more, I’ve also given it a hover effect to darken the background a little.

.back-to-top {
    position: fixed;
    bottom: 2em;
    right: 0px;
    text-decoration: none;
    color: #000000;
    background-color: rgba(235, 235, 235, 0.80);
    font-size: 12px;
    padding: 1em;
    display: none;
}

.back-to-top:hover {    
    background-color: rgba(135, 135, 135, 0.50);
}
scroll-to-top-with-css

The jQuery

First off we need to add jQuery to our page, you can do this by adding a script tag like this

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

Or, if you’re using WordPress like this using add_action and wp_enqueue_script

function theme_enqueue_script(){ 
    wp_enqueue_script('jquery');  
}
add_action('wp_enqueue_scripts', 'theme_enqueue_script');

The actual jQuery function is pretty simple, first we set our offset (after how much scrolling from the top we want the button to appear) and how long we want the scroll to top effect to last. We don’t want it to be too quick, but if it’s really slow it will be annoying. I’ve set it here to half a second.

We then need to make our button visible when the user scrolls. To do this we use the jQuery scroll function. In this function we grab the current scroll position using scrollTop, check to see if it is greater than our offset and if it is we show the button using the fadeIn function. If it’s not we make sure the button is not visible using the fadeOut function.

To actually scroll to the top, we need to intercept the click event on our button. First we prevent the default click from being triggered, and then we scroll back to the top using the animate function, passing in our duration. Finally we return false to ensure that no other events are raised after this.

jQuery(document).ready(function() {
    var offset = 220;
    var duration = 500;
    jQuery(window).scroll(function() {
        if (jQuery(this).scrollTop() > offset) {
            jQuery('.back-to-top').fadeIn(duration);
        } else {
            jQuery('.back-to-top').fadeOut(duration);
        }
    });
    
    jQuery('.back-to-top').click(function(event) {
        event.preventDefault();
        jQuery('html, body').animate({scrollTop: 0}, duration);
        return false;
    })
});

And here it is, a quick, simple but effective way of getting back to the top of a page.

Author: Jonathan Schnittger
A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio
  • http://wwww.minecraftchannel.net/ Minecraft

    Thanks for giving me the useful information. I think I need
    it. Thank you

  • Byron

    Thanks! This is very useful :)

  • katie

    can you show me, where can i add these codes step by step? :( thanks

  • Dyl

    Thanks for this. Works great. Just wondering if there is an easy way to make it stay sittting above the footer div once the page is scrolled all the way to the bottom?

    • Samyson Aguilera

      Hey, the way to fix
      this is change:
      a href=”#” class=”back-to-top”>Back to Top
      to
      a href=”#” class=”back-to-top” style=”display: none;”>Back to Top
      And this should fix the problem :)
      Have a nice day :)

  • Giorgia

    Thank you. Nice work!

  • Juth

    Thank you very much!

  • EBI

    best solution so far, many thanks!

  • Damn-Deal-Done

    Hello. Is there a way to stop it loading by default?

    • Damn-Deal-Done

      Is that a no? The to top link is visible when the page loads.

      • http://www.damirhara.com damdeez

        You can try adding “display: none;” to the parent element.

  • http://tomdurkin.me Tom Durkin

    Works a charm, thanks!

  • http://www.jugarjugar.net/ Jugar Jugar

    Seems like it’s quite the investment and this is pretty good. But I really have lots of questions for this operation. There seems to be something unusual

  • zoogli

    ff

    • zoogli

      dd

      • zoogli

        gg

  • riamerriprice

    WTC4 Last few years I would be really, really low on $$ and debts were eating me from all sides!! that was UNTIL I found out how to make money on the internet. I visited surveymoneymaker point net, and started doing surveys for money, and surely i’ve been great amounts more able to do my things! I am so glad, that I did this!!! – ZPxa

  • Guno

    Smooth as butter. Thanks

    • Just me

      You said it!

  • MadeGlobal

    I added the following to the jquery so that I didn’t have to change each of my pages to add the html part of the button. This is, I think, also faster from a page loading perspective…
    $( “html” ).append( “Back to Top“);

    • JRem

      Would you please guide me on how to implement this? I am a newbie! Thank you.P { margin-bottom: 0.08in; }A:link { }

  • pixelauflauf

    Vielen Dank, geht gut!

  • Kris

    I tried to do this on my PHP page but it’s not working unless I remove all my absolute & relative elements from the page – any idea how to do this when using a page with multiple of these elements?

  • Prasad

    Thanks for posting such an useful code…. So smooth as ice cream

  • OpenCode

    Great work. Thanks!

  • Usama Ejaz

    Thank you. I used this one over many tutorials :)
    Now the code is live on my site http://www.mynoblecare.com ^_^

  • Степан Косолапов

    Спасибо – Thanks

  • PhpDude

    Smart and easy to implement. And it works. Great.

  • Alauddin mondal

    Great sir I got it very comfortably

  • Pr Wodux

    Its not working in IE 8

    • Eetheart

      Nothing is working in IE8. Get over it. Update. Or redirect your users to a site that asks them to pick a better browser or update their current.

  • Nikia

    This was great – thanks so much!

  • Jane

    I love you!!

  • Guest

    Great snippet… i had to tweek it a little so that i can have it in angular.

    So anyway if someone needs it – i posted it for all to use.

    https://gist.github.com/srfrnk/8887352

    Enjoy.

  • Saji

    Thanks. You save my time. :)

  • Max

    Thanks! Can you tell how to scroll to the footer and the part that I choose please.

  • yuck_foo

    Works great in FF, Safari, and even Explorer (egad!) but for some reason Chrome makes the button very jittery. Any ideas? Thanks

  • Tony Gray

    Thanks. This worked perfectly!

  • schnoedeltroedel

    Thank you very much! Never implemented a task that easy! Worked like a charm!

  • Chill Out

    class id=”I love it thank you” ;)

  • http://javabynataraj.blogspot.com/ Mdhar

    can i use the same method “wp_enqueue_script” method call for blogger too? Or is there any other way? Please let me know.

  • MD. AMANUL HUQUE ONY

    Awesome article, it helped me :)

  • Samyson Aguilera

    Hey guys, if you’re finding that the button is appearing as the page loads, and only disappearing once you start scrolling, the way to fix this is change

    Back to Top
    to
    Back to Top
    And this should fix the problem :)

  • Pawel

    Thank you!!!!!!! for great turtorial!!!

  • Rick

    Helped me out alot, Thanks

  • http://www.miscy.net/ Max Pen

    Good read, useful share.

  • http://www.utkuobuz.com/ System Architect

    Thank you so much :)

  • chliang

    Great post! Got it working. I had to fix an edge case where if you refresh your page and you’re already scrolled down, the button doesn’t show up. Can be fixed by performing the check in the .scroll(…) during .ready(…) as well.

  • Randy Marsh

    Works perfectly on my custom WordPress theme! Thank you for this simple and light weight solution!

  • PC Users

    Very good only missed the “button” go to the bottom

  • Neil Wilkinson Cave

    yuck_foo (!) said;

    “Works great in FF, Safari, and even Explorer (egad!) but for some reason Chrome makes the button very jittery. Any ideas? Thanks”

    I am experiencing the same issue, and it’s also jittery on the phone / tablet version of chrome

  • Opperman

    Thank you for this!

  • Matt Johnson

    Awesome, works a treat, thanks!

  • Bhaskar Dabhi

    Thanx buddy!!
    I didnt get why to use return false in ‘.back-to-top’ click handler when u already preventing default action? Any specific reason?

  • ULazdins

    Thank you!

  • Allen Murgondy

    Thanks for sharing this, a great example, a hard to find :)

  • Paul John

    thanks

  • Lahiru SupunChandra.

    Oh my god you are awesome…cooooooooooollllll… Thanks you so much.. (Y) <3

  • mbeddedsoft

    Hello. First off let me say this is cool. However, I’m having a bit of a problem. Once the button is displayed it remains visible after scrolling to the top of my page. Any ideas on what could be wrong? Thanks in advance.

    • mbeddedsoft

      Never mind. I figured it out right as I posted. I forgot the . before the class name ‘back-to-top’ in the .fadeOut() call. :D