August 19, 2014

How to make smooth scroll to top and visible on scroll?

Smooth scroll to top

Scroll down to make the scroll to top button appear. On click of it the page scrolls smoothly to the top of the page. The scroll will be visible only after a page scroll.

HTML

<p>Contents...</p>
<a href="#" class="scrollup">Scroll</a>

CSS

.scrollup{
    position: fixed;
    bottom: 2em;
    right: 0px;
    text-decoration: none;
    color: #fff;
    background-color: #000;
    font-size: 12px;
    padding: 1em;
    display: none;
}
.scrollup:hover {    
    background-color: #999;
}

jQuery

$(window).scroll(function() {
    if ($(this).scrollTop()) {
        $('.scrollup').fadeIn();
    } else {
        $('.scrollup').fadeOut();
    }
});

$(".scrollup").click(function () {
   $("html, body").animate({scrollTop: 0}, 1000);
});

Attachment

I have used external attachments.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Note

You should add more contents to your HTML or give maximum height to the body in CSS, to see it working.

demo

No comments:

Post a Comment

Popular Posts

Views