codeofaninja
website

Scroll Page to Top Using jQuery

Photo of Mike Dalisay
Modified Saturday, June 1, 2013
by - @ninjazhai
There are some friends who asked me how I did this "back to top" feature of our blog. For a live demo, try to scroll down this page, you will see an "up arrow" image on the lower right corner. When you click it, it will get you to the top of this page.

Code of a Ninja Scroll Page To Top

For me this is another cool feature for any website that make use of long vertical scroll bar. The user can instantly go the the top of the page easily, just in one click! So here's the HTML, CSS and jQuery code I used:

HTML - this will make our 'up arrow' image shown.
<a href="#" class="ninjaUp" title='Back to top...'>Scroll</a>

CSS - our arrow image looks a little blurred, but when you hover your mouse on it, it will be emphasized, thanks to CSS opacity!
.ninjaUp{
    width:128px;
    height:128px;
    opacity:0.3;
    position:fixed;
    bottom:10px;
    right:10px;
    display:none;
    text-indent:-9999px;
    background: url('https://lh6.googleusercontent.com/-jqrSBwq8jN8/UYSas7Y9_eI/AAAAAAAAFGA/AESC5Kc64-I/s128/1367662569_upload_arrow_up.png') no-repeat;
}

.ninjaUp:hover{
    opacity:0.6;
}

jQuery - this will detect scrolling, do the fade effect and scroll to top animation!
<script type="text/javascript">
$(document).ready(function(){

    // detect scroll
    $(window).scroll(function(){
    
        // if the user scrolled the page more that 200 pixels, show the 'up' arrow image
        if ($(this).scrollTop() > 200) {
            $('.ninjaUp').fadeIn();
        } 
        
        // hide the 'up' arrow image
        else {
            $('.ninjaUp').fadeOut();
        }
        
    });

    // when the user clicks on the 'up' arrow image, it will scroll the page to the top
    // it will occur in a second (see 1000 value below)
    // you can change that value if you want to make the scroll faster or slower
    $('.ninjaUp').click(function(){
        $("html, body").animate({ scrollTop: 0}, 1000);
        return false;
    });

});
</script>

How about if I don't what to "scroll" it. Easy, you just have to make value to "0", so the code will be like this:
$('.ninjaUp').click(function(){
    $("html, body").animate({ scrollTop: 0}, 0);
    return false;
});

It is beautiful! Thanks to jQuery functions like jQuery scroll and animate and CSS Opacity!
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
 
 
Fundamentals
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.