Contact Us
  • How to Implement a jQuery Back-to-top Button for your Responsive Website

    The advent of mobile-specific websites and responsive (“Responsive Web Design” aka “RWD”) websites has demonstrated the need for a back-to-the-top button at mobile-device widths where such a feature might not be needed at desktop width.

    A jQuery Top Button for your Long Web Pages

    Here’s how to implement a jQuery “Back to Top” button in your site’s footer that, when clicked, smoothly scrolls the page up to the very top:

    1) Add the HTML to your website’s footer content

    <a class='go-to-top' href='#wrap' title='back to top'>Back to Top</a>

    The HREF element will have to be the very first element after the opening <body> tag. In my case it was the #wrap div.

    2) Add the styles for this Back to Top link. Tailor the following to suit your site (eg you’ll have to create your own button graphic).

    a.go-to-top {
    background: url('images/arrow-to-top.png') no-repeat center center;
    width: 35px;
    height: 35px;
    position: absolute;
    right: 30px;
    bottom: 30px;
    text-indent: -9999px;
    font-size: 0;
    cursor: pointer;
    outline: 0;
    }

    To position the button more precisely in different viewports (browser screen widths), you can add the following rules to the appropriate breakpoints (the browser widths at which a responsive website reformats), and adjust accordingly:

    a.go-to-top {
    right: 15px;
    bottom: 120px;
    }

    3) Add this script right before the closing </body> tag. I found that placing the script in the header caused a conflict with another jQuery script, requiring that I place it before the </body> tag. I included the first line which calls the jQuery library from Google even though a local jQuery library is already referenced in the header (the jQuery in the header was incompatible with this script).

    <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
    <script>
    $(function () {
    $('.go-to-top').click(function () {
    $('html,body').animate({
    scrollTop: 0
    }, 500);
    return false;
    });
    });
    </script>

    You can see this back-to-top button in action in this responsive WordPress website we developed here at HyperArts.

    (I’ve adapted this “back-to-top” functionality from this tutorial. I removed the fixed position of the button within the viewport, however, choosing instead to have it appear only in the footer.)

    If you have any questions, feel free to ask in the Comments. Happy coding!

    Comments

    1. Justin Tuttle says:

      Most website theme already has this built in but still this comes handy…

    2. Thanks this helped me get the go to top of page link to work. I would like to add that there is no need to include jQuery since every build of WordPress already has it integrated.

      Thanks, again, Virgil

    Speak Your Mind

    *