Scroll to top of page in JavaScript

Today I'll show you how to scroll to top of page in JavaScript. There are some friends who asked me how I did this "back to top" feature of our blog.

Imagine you 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 makes use of a long vertical scroll bar. The user can instantly go to the top of the page easily, just with one click! So here's the HTML, CSS, and JavaScript 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!

    background: url('') no-repeat;


jQuery - this will detect scrolling, do the fade effect and scroll to top animation!

<script type="text/javascript">

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

    // 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
        $("html, body").animate({ scrollTop: 0}, 1000);
        return false;


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:

    $("html, body").animate({ scrollTop: 0}, 0);
    return false;

It is beautiful! Thanks to jQuery functions like jQuery scroll and animate and CSS Opacity!

Hi! I'm Mike Dalisay, the co-founder of, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]

I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.