Create Scroll to Top Button jQuery ScrollTop - CodingTuting


How to Create back to Top Button in our Website?

Scroll Button Back to Top is very important for a website. It gives a very good user interface, and the user doesn't need to too much scroll to go to the top of the page.

Go to top Scrolltop button in jQuery HTML
Add jQuery ScrollTop & Scroll button top | CodingTuting | Image By mmi9 from Pixabay

Here we have a very simple method to add Scroll Top button our website.

We will make a back-to-top button using HTML, CSS, and jQuery. We'll use "jQuery scrollTop()" method for this. It is very easy.

Follow the below step to create a "scroll to top jquery"


Step 1
Create a scroll-top button at the bottom of the page
<button id="top-btn"> Top </button>

You can use any icon or symbol instead of the button text "Top"


Step 2

Add CSS to give style to the Scroll-Top button

<style>
 
    html 
    {
        scroll-behavior: smooth; /*Mandatory for smooth scroll*/
    }
  
    #top-btn
    {
        position: fixed; /* Mandatory */
        right: 20px; /* Mandatory */
        bottom: 20px; /* Mandatory */
        padding: 9px; /* Mandatory */
        border-radius: 5px;
        color: #fff;
        background-color: #5089b9;
        border: none;
        display:none;
    }
 
    button#top-btn:hover
    {
        background-color: #2978bb;
    }

</style>

You can modify the style of the button according to your website theme.


Step 3

Add jQuery before closing the </body> tag

<script data-src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>

Note - Don't add jQuery again if you've added already.



Step 4

Add this jQuery code before closing the </body> tag

$(document).ready(function(){
  
    $(window).scroll(function(){
  
        if($(this).scrollTop() >= 500) /* Set limit according to your need */
        {
            $("#top-btn").fadeIn();
     
            $("#top-btn").click(function(){
                $(window).scrollTop(0);
            });
         }
         
         else
         {
             $("#top-btn").fadeOut();
         }    
    });  
  
});





Thanks for Reading


Hi, I'm Jignesh Panchal. I'm a Web Developer & Designer. I've started this blog to help the programmers using my experience and skills. You will get solutions and tips about Programming, Web Development etc.

Share this

Related Posts