How to make a Smooth Scrolling “Back To Top” Button with jQuery

Filed under: Scripts — Tags: , , ,

A common usability feature on a lot of sites is a “Back to top” link at the bottom of long pages, allowing users to quickly get back to the start of the document without scrolling.

How to make a Smooth Scrolling Back To Top Button with jQuery

Wonder how it was made? I’ll tell you. It’s quite simple. What you need is a link containing the text, apply some CSS and add an event using jQuery.

First, create the link:

Add this at the bottom of your page where you want to display Back to Top link.

<p id="back-top"><a href="#top">Back to Top</a></p>
Then add style to it

Add this in your CSS file or inside <style> tag.

#back-top {
	display:block;
	height:30px;
	width:110px;
}
#back-top a {
	width: 108px;
	height:28px;
	border:1px solid #bbb;
	text-decoration:none;
	display: block;
	text-align: center;
	font: 12px Arial, Helvetica, sans-serif;
	color: #808080;
	background:#ededed;
	line-height:28px;
	font-weight:700;

}
#back-top a:hover {
	color: #151515;
	border:1px solid #bbb;
	text-decoration:none;
	background:#dedede;
}
And last, the jQuery code:

Add this before the ending </body> tag.

<script type="text/javascript">
$(document).ready(function(){
		// scroll body to 0px on click
		$('#back-top a').click(function () {
			$('body,html').animate({
				scrollTop: 0
			}, 800);
			return false;
		});
});
</script>

jQuery Library – Add this before the ending </head> tag.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>

WordPress users: Most likely the jQuery library is already being loaded by WordPress, your theme or one of your plugins. At first, skip this section to see if it works, if not, add the jQuery library to your header before the ending </head> tag.

For a live demo check the Back to Top link at the bottom of this page.

Enjoy making your site much cooler.

You might like:

2 Comments so far...
Leave Yours
shkodra

Can i change picture to this button?

March 21, 2013 at 5:02 pm Reply

Thank you for great tutorial. you can see your piece at starfallarcade(dot)com. Lots of joy with your help.

May 9, 2013 at 12:51 am Reply
Leave a Reply