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:
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:
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.back to the top of page
And that is all for today.