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

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>


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);


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(){ 
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) {
        } else {
    jQuery('.back-to-top').click(function(event) {
        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.

A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio More articles by Jonathan Schnittger
  • 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
      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.

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

  • Works a charm, thanks!

  • 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


    • zoogli


      • zoogli


  • 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 ^_^

    • Erin Kelly

      Your site is nice, but it is a little overwhelming on first impression, just a note 🙂

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

    Спасибо – 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

  • 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.



  • 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” 😉

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


    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
    Back to Top
    And this should fix the problem 🙂

    • Siva

      How about inside iframe page?Because there it has to take the main page scroll-page.Not the Iframe scollbar.It is entering into fadein and screen nothing is displayed.
      With out Iframe, for a normal html page it is working fine.
      Did any one came across it?
      Thank you.

    • Thanks! A very helpful post!

  • Pawel

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

  • Rick

    Helped me out alot, Thanks

  • Good read, useful share.

  • 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


  • 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. 😀

  • Jonathan,

    It took me literally 5 minutes to implement this functionality !
    The source HTML file you provided was of great help.
    “Borrowed” the code into the Web2Py layout.html page, which is extended to all the pages of the web site. GREAT !

    Many thanks!

  • Jeff

    Hi Jonathan,

    Thanks for the useful code. Everything is working great for me with a few minor alterations for angular.

    The one question I do have is that when the scroll button is clicked it scrolls very fast – is there any way to adjust that speed?


  • Igor Mironenko

    Thanks 😛

  • limegreende

    Old post, I know, but this is a great tool and worked perfectly on my site as written with only minor changes to the styling. Problem arose when I added a redirect in .htaccess to automatically redirect viewers to a mobile version of the site. Now, trying to go to the one page with this back-to-top code, automatically send to you the mobile version. Any thoughts? Here is the .htaccess code:

    Options +FollowSymlinks
    RewriteEngine on
    RewriteRule ^(application) – [L]
    RewriteCond %{HTTP_HOST} ^website.com
    RewriteRule (.*) http://www.website.com/$1 [R=301,L]
    RewriteEngine on
    RewriteBase /
    # Check if this is the noredirect query string
    RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
    # Set a cookie, and skip the next rule
    RewriteRule ^ – [CO=mredir:0:www.website.com]

    RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
    RewriteCond %{HTTP:Profile} !^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} “acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “wapp|wapr|webc|winw|winw|xda|xda-” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “up.browser|up.link|windowssce|iemobile|mini|mmp” [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} “symbian|midp|wap|phone|pocket|mobile|pda|psp” [NC]
    RewriteCond %{HTTP_USER_AGENT} !macintosh [NC]

    # Check if we’re not already on the mobile site
    RewriteCond %{HTTP_HOST} !^m.
    # Can not read and write cookie in same request, must duplicate condition
    RewriteCond %{QUERY_STRING} !(^|&)m=0(&|$)

    # Check to make sure we haven’t set the cookie before
    RewriteCond %{HTTP_COOKIE} !^.*mredir=0.*$ [NC]

    # Now redirect to the mobile site
    RewriteRule ^ http://m.website.com [R,L]

    • limegreende

      I figured it out – It was actually the AJAX & JQuery. I added code to disable AJAX for that page

      $(document).bind(“mobileinit”, function () {
      $.mobile.ajaxEnabled = false;

  • Siva

    How about inside iframe page?Because there it has to take the main page scroll-page.Not the Iframe scollbar.
    Did any one came across it?
    Thank you.

  • cricket

    for some reason it doesnt work in my safari on my desktop, does on my ipad. this does work however, in my FF desktop. why is that?

  • awesome…thanks!!

  • Freaking terrific. I love this code! Thanks!

  • Erin Kelly

    This is great, but is there a way to put the button in the center of the page? Margin-left and right auto doesn’t seem to be working.

  • denisewheeler

    Fantastic post. Thanks so much for sharing it. I just inserted all the code and it works great. Except the iQuery is showing up in the footer. Is there anyone who can tell me how to fix that?

  • Thank you it helps alot 🙂

  • Fujimaru R

    thanks a lot bro, very helpful 🙂

  • Sajjad Hossain

    Thanks for this nice and easy to understand implementation.

  • Sandy DeShazo

    Works great! Thank you!

Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress