How to Create a Scroll To Top Button

jquery logo.png

On long pages it is often quite nice to provide the user with a button or link to scroll back to the top of the page with a single click.

scrollToTop.jpg

It is possible to use simple javascript to accomplish this. 

However, in this example I would like to animate the scroll so we will be using jQuery.

STEP 1

We first create a simple HTML template and include the link to jQuery:

STEP 2

We can now add some content to the body section. 

I have just used some Lorem Ipsum text but, obviously, you can use anything you wish.

For simplicity, I have edited out many of the lorem text lines and only left a few.

Depending on your code editor you may be able to add lorem text with a simple command like: lorem*20

STEP 3

We can now add a button to take us to the top of the page.

My button has an id of 'toTop'. We will use this id in the jQuery.

Step 4

We can now add the jQuery code:

Line 8: this will ensure the page has loaded and is ready before executing any code.

Line 9: if the #toTop id element has been clicked then we perform a function (line 10 in this case).

Line 10: we target the html and body elements and animate to the top using a slow scroll. The reason we need to use html AND body is that different browsers require different rules.