voidynullness

(mis)adventures in software development...

    
29 May 2015

Smooth scrolling using jQuery

Share
Category Web Development

Smooth page scrolling using jQuery, and a floating scroll to top button.

Just leaving this here so I don’t have to keep looking it up…

Smooth scrolling is a common embellishment for web pages, and it’s possible to implement with surprisingly little code thanks to jQuery.

Creating a link that returns to the top of the current page can be done using an anchor with a URL fragment of “top”:

<a href="#top">Return to top</a>

Thanks to jQuery’s equivalents of CSS attribute selectors, we can easily add a click handler to all anchor elements on the page that implements smooth scrolling using the jQuery animate() function:

$("a[href='#top']").click(function() {
    $("html, body").animate({ scrollTop: 0 }, "slow");
    return false;
});

Floating scroll to top button

A more advanced embellishment is to add a floating button (often fixed in the bottom right corner of the page) that will return to the top. To implement this, first we need an appropriate anchor element somewhere on the web page. Here’s an example using Font Awesome for the up arrow icon:

<a href="#top" class="btn-scroll-to-top" title="Top of page">
  <i class="fa fa-arrow-circle-up fa-fw fa-lg"></i>
</a>

Then we style it appropriately with CSS and fix it’s position:

.btn-scroll-to-top {
    background-color: transparent;
    display: none;
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 5px;
    font-size: 36px;
    font-weight: bold;
    text-align: center;
    text-decoration: none;
}
.btn-scroll-to-top:hover {
    text-decoration: none;
}

That by itself should do the trick (if we were to omit the display: none line). But we can take things a step further, and make the button fade in once the user starts to scroll down the page. Putting it all together with the smooth scrolling, the JavaScript would look something like this:

$(document).ready(function() {
    $("a[href='#top']").click(function() {
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    });

    $(window).scroll(function(){
         if ($(this).scrollTop() > 200) {
             $('.btn-scroll-to-top').fadeIn();
         } else {
             $('.btn-scroll-to-top').fadeOut();
         }
    });
});

Here we’re using the jQuery scrollTop() function to determine how far the page has been scrolled, and toggling the button visibility as appropriate.


 

Comments