jeudi 7 juin 2012

JavaScript: smooth scroll to the top of the page

If you have long pages, it is quite clear that a user will scroll your pages and eventually reach the end of the content area. In some case, however, menus or other relevant elements of the web site will stay at the top of the viewport. How do we create a link which will scroll smoothly back at the top?
We can use a small JavaScript function. Here I explain how...

The function
We are going to insert the following JavaScript function in the head of the document. The link at the bottom of the page will trigger it and immediately the page will scroll up to the beginning.
We are going to benefit from the scrollBy method.
Here's the function:

<script type="text/javascript">
var timeOut;
function scrollToTop() {
  if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
    window.scrollBy(0,-50);
    timeOut=setTimeout('scrollToTop()',10);
  }
  else clearTimeout(timeOut);
}
</script>
As you can see we are using the setTimeout to slow down the scrolling and re-trigger the function until we reach the top of the page.

The HTML
There's not much to say about the HTML part: it is just a link but eventually you can style it appropriately. Just a small side note: because the link has a href="#" it will work even if JavaScript is disabled on the target browser.
<a href="#" onclick="scrollToTop();return false">back to the top of page</a>
And that is all for today.

0 Responses to “JavaScript: smooth scroll to the top of the page”

Enregistrer un commentaire

All Rights Reserved Blogging Tips | Blogger Template by Bloggermint