Create A Back To Top Button With HTML, CSS & JQuery

When the content of a web page is too lengthy, the user may have to scroll the page from bottom to top once he reaches the end of the page. By providing an option for the user to scroll back to the top of the page by clicking a simple floating icon, we can achieve a good UI experience(especially on mobile devices). We can create the back-to-top button using plain HTML, CSS, and JQuery.

In this post, we will create a simple scroll to the top or back to the top button using HTML, CSS, and JQuery. We are going to use a simple image as back to top button.

Table of Contents

Create an HTML page & add back-to-top button element

The first step is to create a simple HTML page with the required elements. Let’s create a simple HTML page as shown below. Here we have added a paragraph to display some random text. an anchor tag for displaying our back-to-top button, with the class as goToTop.

   <p> This is HTML content. </p> 
   <a href="#" class="goToTop"></a>

Add CSS for HTML content

By default, the page will not display our go-to top button will not be on the bottom right corner of the page. Let’s add a few CSS to make it work as expected. Add the following styles to the tag of the page.

 .goToTop {    
    padding: 35px; 
    bottom: 30px;    
    right: 10px;
    background: url('arrow_up.png') no-repeat 0px 20px; 
    z-index: 2000;
body { 
    height: 200%;

We are using a background image as the button icon. Note that the image should be in the same directory where the HTML page.

The position:fixed attribute fixes the position of the button image in the right corner of the page irrespective of screen resolution. By default, the display attribute value is none, which will hide the button whenever we are on top of the page.

We have set the height attribute of the body to 200% as our page does not have much content to scroll.

Import JQuery library and add JQuery code

Once our HTML and CSS structure is ready, finally add the functionality by importing the JQuery library and adding a script for implementing our functionality.

Import the JQuery library from JQuery CDN by adding it to the header of HTML.

  < script src=""/>

Then add the following JQuery script between < script> tag.

When the user scrolls the page and the vertical page position crosses more than 100, our back-to-top button is displayed.

       if ($(this).scrollTop() > 100) { 
       else { 
    //Click event to scroll to top 
        $('body').animate({scrollTop : 0},700); 
        return false; 

On clicking the scroll to top button, we assign the vertical page position attribute value with 0, and the page scrolls back to the top.

Finally, our simple go-to top button is ready..!!



In this article, we learned how to create a back-to-top button using plain HTML, CSS, and JQuery.