Powered by eUKhost®

Announcement

Collapse
No announcement yet.

How to smoothly scroll back to the top of the HTML page using jQuery JavaScript library

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to smoothly scroll back to the top of the HTML page using jQuery JavaScript library

    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:

    Code:
    <script type="text/javascript">
    	$(document).ready(function()
    	{
    		$('.link_top').click(function()
    		{
    			$('html').animate({scrollTop: 0}, 600);
    		});
    	});
    </script>
    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:

    HTML Code:
    <p class="text anchor-top"><a href="javascript:void" class="link_top">&uarr;</a></p>
    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)
    Last edited by eUK.Ben; 06-07-2013, 12:50. Reason: Indicating the animation speed patemeter is in milliseconds
    Find us on Twitter and Facebook

    Need to contact us?
    Customer Support: Client Area - 0800 862 0380 (option 2)
    Customer Relations: [email protected] - 0800 862 0380 (option 3)
    Sales: [email protected] - 0800 862 0380 (option 1)




    The opinions or views expressed above are not necessarily the opinions or views of eUKhost Ltd.
ban-img
Working...
X