Trang

Thứ Năm, 18 tháng 7, 2013

Smooth Page Scroll to Top with jQuery [JQuery]

If the web page has lots of content, its a good idea to provide visitors with an easy way to quickly scroll to the top of the page. In this tutorial, we will create smooth page scrolling effect for returning to the top of the page using jQuery.
We will create a button at a fixed position on the bottom right of the page, so that we once click it, it scrolls up with an nice animation rether than a page refresh or a straight jump to the top. We will make the button visible only if the page is scrolled down, instead of being always visible.
First, lets add the button link on the page, so that when it is clicked, we can scroll the page to the top.
<a href="javascript:void(0)" class="scrollup">Scroll</a>
Now we can add CSS to the above button link:
.scrollup{
    width:40px;
    height:40px;
    opacity:0.3;
    position:fixed;
    bottom:50px;
    right:100px;
    display:none;
    text-indent:-9999px;
    background: url('icon_top.png') no-repeat;
}
As you can see, we have defined fixed position for the button which is 100px from right and 50px from the bottom. I have used the text-indent to hide the text and display the icon for the button. The disply:none makes the button invisible initially.
Now we want to make the button visible if the page is scrolled down. We can do that with jQuery scroll event.
$(window).scroll(function(){
        if ($(this).scrollTop() > 100) {
            $('.scrollup').fadeIn();
        } else {
            $('.scrollup').fadeOut();
        }
    });
The scrollTop gets the current vertical position of the scroll bar. If it is greater than 100px, it fades in the .scrollup button, otherwise fades out. So, when we scroll down the page more than 100px, the button should fade in, and if scroll up to the height of less than 100px it should fade out.
The next step is to to scrolling to the top smoothly, if the button is clicked. We can do use the click function for that.
$('.scrollup').click(function(){
    $("html, body").animate({ scrollTop: 0 }, 600);
    return false;
    });
The scrollTop:0 scrolls to the very top of the page, at 0px position, and the 600 represents the duration of animation in milliseconds. The Higher values indicate slower animations. You can also use ‘fast’, ‘slow’ or ‘normal’ instead of milliseconds.
Here is complete jQuery Code:
<script type="text/javascript">
    $(document).ready(function(){
 
        $(window).scroll(function(){
            if ($(this).scrollTop() > 100) {
                $('.scrollup').fadeIn();
            } else {
                $('.scrollup').fadeOut();
            }
        });
 
        $('.scrollup').click(function(){
            $("html, body").animate({ scrollTop: 0 }, 600);
            return false;
        });
 
    });
</script>
Demo
Nguồn: http://gazpo.com

Không có nhận xét nào:

Đăng nhận xét