How to Add a Simple Scroll To Top Link to Your Website Using jQuery

Check out my other posts and tutorials on Web Development!

Toss in the HTML

Place your scroll link inside your closing body tag:

<a id="scrollup">Scroll</a>

Style It

We want to set the display property to ‘none’ since the scroll link will fade in as we approach the bottom of the page.

Be careful here with link hover styles. If you have universal hover transitions set in place you may have to set transitions to ‘none’ for the scrollup class as to not hinder the jQuery fadeIn we work with in the next section.

#scrollup{
    background: url('images/scroll.png') no-repeat;
    width: 40px;
    height: 40px;
    position:fixed;
    bottom:50px;
    right:20px;
    display:none;
    text-indent:-9999px;
}

Link to jQuery

Add a link to Google’s jQuery library just before your closing body tag:

<script src="https://code.jquery.com/jquery-latest.js"></script>

Make it Work

Here we are telling the To Top link to fade in one we’ve scrolled past the 250px mark from the top of the page, otherwise fade back out. You can adjust the speed at which the page returns to top by altering our animate time, which is currently set to 1 second (1000 ms).

(function($) {
    $(document).ready(function(){
 
        //When distance from top = 250px fade button in/out
        $(window).scroll(function(){
            if ($(this).scrollTop() > 250) {
                $('#scrollup').fadeIn(300);
            } else {
                $('#scrollup').fadeOut(300);
            }
        });
 
        //On click scroll to top of page t = 1000ms
        $('#scrollup').click(function(){
            $("html, body").animate({ scrollTop: 0 }, 1000);
            return false;
        });
 
    });
})(jQuery);

By now, you should see a similar back to top link on this site.

Leave a Reply

Contact Us

Subscribe

Subscribe to our blog to receive latest news and tutorials on Web Design, Development, SEO, and more!