Spread the word

Sunday, July 17, 2011

How to Create a Link To Smoothly Scroll To The Top of a Page by jQuery

"Go to top" is a very popular link that we use to put into web pages when pages tend to be long and users always need to go back to the top of the page to avail the options. Users can obviously go back by scrolling up and up and up. But we can also provide them with an option at the bottom of a page, clicking which will automatically take the user to the top of that page.

The most natural and effective way to do it is to place a "quick link" or "inpage link" which should be linked to the ID of the topmost element on the page.

Example of go to top link on a webpage:


<html>
<body>
  <div id="header">header content here...</div>
  <div id="content">page content here...</div>
  <div id="footer"><a href="#header" id="goToTop">go to top</a></div>
</body>
</html>

Now when anyone clicks on the "go to top" link the browser points him/her to the top of the page i.e. where the element div with ID "header" is located in the page.

But the problem is that the browser scrolls up the page in an instant making the user a bit surprising. So we can remove that element of unwanted surprise by let the browser scroll smoothly to the top of the page. For that we are going to need some JavaScript goodies and we will be doing that here using the jQuery framework. If you know nothing about then also its fine cause you will just need to include a JavaScript file and a very small JavaScript code in the <head> of your page.

Scroll a Page Smoothly to the top with jQuery

Include the latest jQuery framework from here - http://code.jquery.com/jquery.min.js, by adding the following line in the <head> section of your page.
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
After this, just add the next piece of code below it, within the <head> section of your page.
$(function() {
  $('#goToTop').click(function() {
  $('body,html').animate({scrollTop:0},800);  
  });
});
What this small piece of code does is that it listens to the element with ID "goToTop", and when it is clicked it smoothly scrolls the page to the top. The 2 parameters of the "animate" jQuery function are the action to perform and the speed with which it will perform, respectively.

So now you can put this to any of your pages and get them smoothly scrolled to any position any time users click on some particular elements on your page. but never forget to have the quick link to the top element's ID cause if JavaScript doesn't work or if some user disables JavaScript for security issues then also your go to top link will work without JavaScript.

1 comments:

Smotra said...

Good!!!

Post a Comment