Powered by Blogger.

Contact

Popular Posts

Sunday 4 August 2013

Scroll to the top of a webpage with jQuery

 

The Javascript

First In Head Put This Code
<head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
 </script>
</head> 
 
The following Javascript will change all <a href="#top"> links to scroll to the top instead of the instant jump that normally happens when the link is clicked.
1$(document).ready(function() {
2    
3    $('a[href=#top]').click(function(){
4        $('html, body').animate({scrollTop:0}, 'slow');
5        return false;
6    });
7
8});
Note the "return false;" line. This is required otherwise the default action will be done and the instant scroll will happen instead of the nice animated scrolling effect.
The position the document is scrolled to can be different by changing the scrollTop value, the speed by changing the 'slow' value and what appears in the href by chaging the #href value.
Note that an <a name="top"></a> anchor should still be present in the page for browsers that do not have Javascript on or support jQuery.

The HTML

1<a name="top"></a>
2...
3<a href="#top">Back to top</a>
The <a name="top"> does not have to be present, but see the note above about supporting browsers without Javascript on etc.
Categories: ,

0 comments:

Post a Comment