If your page is populated with bunch of contents, it would extend the height of your page which your visitor need to scroll all the way to the bottom to read everything.

After reading the whole content, there are only two things your visitor will do, close the page or scroll back to the top which your visitor might think that it would be nice if there is a button that will take them back to the top of the page.

Adding a back to top button is a great functionality that can add an awesome browsing experience to your website. By just clicking the button, your visitors will be taken back to the top of the page. With the little help of jQuery animation, we can add a nice smooth scrolling effect that will surely amaze your visitors.

It’s not difficult to achieve this functionality. All you need to do is add 3 lines of HTML, few CSS to style our button, and a few lines of jQuery to achieve the smooth scrolling effect.

The HTML

Paste the html code below anywhere in the page as long as it is inside the <body> tag. In the demo, i placed it right after the opening <body> tag.

<a href="#" class="to-top-btn">
	<img src="img/go-top.png" alt="back-to-top">
</a>

The CSS

The CSS below will add a little styling to our button. In this tutorial, the button is hidden by default and will fade in when the page scroll to an offset greater than 400 pixels. You can choose to always show the button by removing the display property.

.to-top-btn {
	position: fixed;
	bottom: 20px;
	right: 30px;
	text-decoration:none;
	background: #FFFFFF;
	color: #454440;
	padding: 10px;
	border-radius: 5px;
	display: none;
}

The jQuery

Finally, include the jQuery library into your page template,

<head>
	...
	<script src="js/jquery.min.js"></script>
</head>

And paste the jQuery snippet below into your page template (inside the <script> tag or into your JavaScript template).

jQuery(function($) {
	//lets handle the button click event
	$('.to-top-btn').on('click', function(e) {
		$('body, html').stop().animate({scrollTop: 0}, 'slow', 'swing');
		e.preventDefault();
	});

	//lets show the button when the page scroll to about 400 pixels
	//change the value to your desired offset
	$(window).scroll(function() {
		if($(window).scrollTop() > 400){
			//show the button when scroll offset is greater than 400 pixels
			$('.to-top-btn').fadeIn('slow');
		}else{
			//hide the button if scroll offset is less than 400 pixels
			$('.to-top-btn').fadeOut('slow');
		}
	});
});

That’s it. Your back to top button is all set. See the demo using the link below to see this tutorial in action.