In this article, you’ll learn how to create a scroll-to-top button using JavaScript and jQuery.

How to Create a Scroll-to-Top Button Using JavaScript

You can add a scroll-to-top button to your website using the following code snippet:

HTML Code

Here, a basic structure of the webpage is created with dummy data. You only need to focus on the scroll-to-top button.

The scroll-to-top button points to the top of the page using the #top id. #top is the id of thetag. The icon of the scroll-to-top button is created using font awesome.

JavaScript Code

The scroll-to-top button is displayed and hidden according to the following conditions:

When the page is loaded, the scroll-to-top button is hidden. The scroll-to-top button is kept hidden until the page is scrolled 200 pixels. You can change the pixels as per your requirement.

CSS Code

The above CSS is used to style the scroll-to-top button and the web page. You can play with the CSS and style the button according to your requirement.

How to Create a Scroll-to-Top Button Using jQuery

You can add a scroll-to-top button to your website using the following code snippet:

HTML Code

Here, a basic structure of the webpage is created with dummy data. You only need to focus on the scroll-to-top button.

When this button is clicked, the page is scrolled to the top. This will be functional after adding the jQuery code.

jQuery Code

Here, the show class is added to the button element if the user scrolls more than 300 pixels on the web page. This show class makes the button element visible. By default, the visibility of the button element is kept hidden. More details about the button are in the following CSS code.

CSS Code

The above CSS is used to style the scroll-to-top button and the web page. You can play with the CSS code and style the button according to your requirements.

Now you have a fully functional scroll-to-top / back-to-top button. If you want to have a look at the complete source code used in this article, here’s the GitHub repository of the same.

Note: The code used in this article is MIT Licensed.

Learn More About User Experience

User experience focuses on whether a product meets the needs of its users. If you’re a designer or a developer, you’d do well to follow UX design principles and create awesome products. If this field interest’s you, you must follow the correct path to get started.