Hovering Go to top button with smooth scroll, using html and jquery

This article demonstrate how you can easily create a go to top button on your blogs or website, whenever yo provide a user good long read you must provide a go to top button. In this lazy world no body likes to scroll all the way back to top


Its always a good idea to give your visitors something easy to do while they stay on your blog or website. Now consider if the visitors are reading on a long post its they does not really like to scroll all the way up to use the menu.

So, should we have a menu down there ?

No, of course not, this is a bad idea to put the main menu down there, neither its a general website practice. So a little solution is to put a “Go to Top” link which will take you on the top.

How simple is that ?

  • 1. very little HTML
  • 2. little more CSS
  • 3. littl more than that, jQuery.

First thing first. Place a link on your website that says “Back to Top” or “Go to Top” or even you can place an image with some icon too. Do whatever way suits you.

Go to Top

you can place it wherever you like, but my advice is to put is just after the body tag. Why? well, because actual position will be fixed, and will be given by CSS.

#top {
    position: fixed;
    bottom: 20px;
    right: 0px;
    text-decoration: none;
    color: #000000;
    background-color: #ececec;
    opacity: 0.50;
    font-size: 12px;
    padding: 10px;
    display: none;
}

#top:hover {
    background-color: #dddddd;
    opacity: 0.80;
}

This will make the link appear in the lower right part of the screen and it will be there always. we have made it hidden because we don’t want it to be there always. We will need it to appear when the user scroll down.

for that purpose we will use jQuery.
before going further make sure to include the jquery in your document body.

<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js"></script>

and put following code in the script tag.

$(document).ready(function(){
	var offset = 200;
	var time = 300;
	$(window).scroll(function(){
		if($(this).scrollTop() > offset){
			$('#top').fadeIn(time);
		}
		else{
			$('#top').fadeOut(time);
		}
	});

	$('#top').click(function(event){
		event.preventDefault();
		$('html, body').animate({scrollTop: 0}, time);
		return false;
	})
});

Now what we have done here is, we are checking for the offset, and if this offset is reached, the link appears. We have given it a fadeIn effect. and when we move out of the offset, it fades out.

And on clicking the link, it scrolls all the way up to the page.

Pretty simple, isn’t it? Feel free to Leave your comments.