How to make webpage scroll to top of page using jquery

I remember me always trying to figure out how to make a page scroll to certain section of a website. I mean it was like magic when I first came across it. I was stun! I later tried to find tutorials on how to do it and let me tell you I had no luck. In this tutorial I will teach you how to add a nice anchor link scroll effect to your website using jquery/ HTML.

How does it work

Whenever you click on a certain link, the page will scroll to that specific link. For example if were to have a long portfolio page and it took forever to reach the bottom I might want to add a link at the bottom of my website that says Back to top and when visitors click on that link the page would scroll to the top.

Script

Add code below to head section or to a separate javascript file. Tells the document to scroll

$(document).ready(function(){
	$(".scroll").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();

		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;

		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split("#");
		var trgt = parts[1];

		//get the top offset of the target anchor
		var target_offset = $("#"+trgt).offset();
		var target_top = target_offset.top;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});
});

HTML

Add the code below after your head section. I did not include the entire html but you can download it or view the demo.

<body>
<div id="top">
<h1>Thanks for coming to the top</h1>
</div><!--end top-->

<div id="middle">
<h1>Thanks for coming to the middle</h1>
</div><!--end middle-->

<div id="bottom">
<h1>Thanks for coming to the bottom</h1>
</div><!--end bottom-->

<p><a href="#top" class="scroll">Go Top</a></p>

<style>

#top{
height:500px;
background:maroon;
margin-bottom:20px;
}

#middle{
height:500px;
background:olive;
margin-bottom:20px;
}

#bottom{
height:500px;
background:teal;
margin-bottom:20px;
}
</style>
</body>

Razvan Sava the author

Razvan is the founder of Webdevtuts. He is also a web designer & developer who loves to design and develop websites. If you're looking for him you can find him via @webdevtuts
  1. Fraser Revie says:

    This code is simple enough but if you wanted to use an external JavaScript you could use something called tinyscroll, it would do what arbel-designs did in their piece. Sorry it’s a bit outdated but thought it could prove useful if somebody else wanted to know.

Leave a Reply