jQuery

jQuery Scroll To Top Of Page Examples

If you ever wondered how to scroll to top of page using jQuery, then here is the perfect snippet for you. In this article, I am going to share two snippets that will let you scroll to top of page and even control the speed at which the scrolling takes place, thus allowing you greater control over the whole scrolling process. Read on to find out more about these copy & use snippets!

Examples to Scroll to Top of Page using jQuery

I am going to show you how you can use jQuery to scroll to top of page very easily, by means of an example. In this example, I am assuming that I have some content as my text, that spans more than one page and a hyperlink at the bottom of the content. I want to be able to click on this hyperlink so that the page automatically scrolls to the top of the page. In order to do this, I am applying a class of “scroll” to this hyperlink and adding code to this using jQuery. So here’s how it’s done:

Example: Use jQuery to scroll to top of page and also control its speed (optional)

<html>
<head>
<title>jQuery Scroll to Top of Page Example</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>

<body>

<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>

<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>
<p>Some content. </p>

<p><a href="#" class="scroll">Go To Top</a></p>
<script type="text/javascript" language="javascript" >

$(document).ready(function(){

	//Scroll slow
	$(".scroll").click(function() {
		$("html, body").animate({ scrollTop: 0 }, "slow");
		return false;
	});

	//Scroll fast
	$(".scroll").click(function() {
		$("html, body").animate({ scrollTop: 0 }, "fast");
		return false;
	});	

	//Scroll in 1 second - 1000 milliseconds
	$(".scroll").click(function() {
		$("html, body").animate({ scrollTop: 0 }, 1000);
		return false;
	});

	//Scroll in 5 seconds - 5000 milliseconds
	$(".scroll").click(function() {
		$("html, body").animate({ scrollTop: 0 }, 5000);
		return false;
	});

});	
</script>
</body>
</html>

Each of the code blocks is commented at it’s beginning, for your easy understanding. When you try the code above, make sure that you comment all code blocks except the one that you want to test as only the first block of code will be executed because they are all linked to the click event of the same html element.

Simple, isn’t it?

Do you know of any other ways to use jQuery to scroll to top of page? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*