There is an easy way to get the user back to the top of the page - simply tack on the hash symbol to a link. But with JavaScript taking over, what if we could create an even better user experience? Instead of jumping the user from bottom to top, why not make it smoothly animate up? This is possible using in JavaScript, and make very easy using the jQuery library. Take a look at the following code:
So what's happening? Of course, the $document).ready() method is to make sure the HTML document is fully loaded before we start executing JavaScript code. Then we simply check whether a link has been clicked, so that code could look like this:
The next line is the animate() method which takes a kind of key-value pair (actually JavaScript Objects - we'll have a tutorial on that very soon). By specifying "scrollTop: 0" we're telling the animate() method to animate scrolling until it is 0 pixels from the top of the HTML document. The last part is setting the speed of the animation in milliseconds. You can view all the patameters of the animate() method in the jQuery documentation.
It's as simple as that. Hope this helps.
Some other tutorials which are similar to this:
How to get the width of the HTML document/web page window using JavaScript? (using jQuery library)
Code:
<script type="text/javascript"> $(document).ready(function() { $('.link_top').click(function() { $('html').animate({scrollTop: 0}, 600); }); }); </script>
HTML Code:
<p class="text anchor-top"><a href="javascript:void" class="link_top">↑</a></p>
It's as simple as that. Hope this helps.
Some other tutorials which are similar to this:
How to get the width of the HTML document/web page window using JavaScript? (using jQuery library)