How to create a back to top button using HTML, CSS and JQuery

When content of a page is too lengthy, user may have to scroll the page from bottom to top once he reaches to the end of the page. It becomes very convenient if we provide an option for the user to scroll back to top of the page on clicking a simple floating icon. This becomes very useful on mobile devices.

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

Following are the steps to create our simple back to top button:

  • Create a HTML page and add back to top button element to it.
  • Add CSS for HTML content.
  • Import JQuery library and add JQuery code.

Create a HTML page and add back to top button element to it

First step is to create a simple HTML page with 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 class as goToTop.

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


Add CSS for HTML content

By default, our go to top button will not be displayed on bottom right corner of the page. Let’s add few CSS to make it work as expected. Add the following styles into 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 have used background image for showing the button. note that the image should be in the same directory, where the HTML page is placed. position:fixed attribute will keep the position of the button fixed irrespective of screen resolution. By default display attribute is set to none, which will hide the button whenever we are on top of the page.

We have set height 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 JQuery library and adding script for implementing our functionality.

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

  < script src=""/>

Then add the following JQuery script between < script> tag. Here, whenever user scrolls the page and the vertical page position crosses more than 100, our back to top button is displayed.

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

On clicking the scroll to top button, vertical page position is set to 0 and page scrolls back to top.

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