How To Create a Scroll Back To Top Button

This example demonstrates how to create a “scroll to top” button that becomes visible when the user starts to scroll the page.

Step 1) Add HTML:
Create a button that will take the user to the top of the page when clicked on:

<a href="#" id="back-to-top" title="Go To Top" class="show">Go</a>

Step 2) Add CSS:
Style the button

#back-to-top {
	background: #e030a8 none repeat scroll 0 0;
	border:2px solid #FFF;
	bottom: 15px;
	color: #FFF;
	cursor: pointer;
	height: 50px;
	line-height: 42px;
	opacity: 0;
	position: fixed;
	right: 15px;
	text-align: center;
	text-decoration: none;
	-webkit-transition: opacity 0.2s ease-out 0s;
	transition: opacity 0.2s ease-out 0s;
	width: 50px;
	z-index: 9999;
	-webkit-border-radius: 50px;
	-moz-border-radius: 50px;
	border-radius: 50px;
	font-size:18px;
}
#back-to-top:hover {
	background: #9a0ae3 none repeat scroll 0 0;
	border:2px solid #FFF;
}
#back-to-top.show {
	opacity: 1;
}

Step 3) Add JavaScript

if ($('#back-to-top').length) {
    var scrollTrigger = 100, // px
        backToTop = function () {
            var scrollTop = $(window).scrollTop();
            if (scrollTop > scrollTrigger) {
                $('#back-to-top').addClass('show');
            } else {
                $('#back-to-top').removeClass('show');
            }
        };
    backToTop();
    $(window).on('scroll', function () {
        backToTop();
    });
    $('#back-to-top').on('click', function (e) {
        e.preventDefault();
        $('html,body').animate({
            scrollTop: 0
        }, 700);
    });
}

Leave a Reply

Your email address will not be published. Required fields are marked *