Learn to create a “Back to top Button” with JavaScript.

I am pretty sure you have seen many types of back-to-top buttons on many web pages, which are useful sometimes.
This little thing really affect the user experience of websites.

so without wasting any more time let’s directly jump on the process.

step 1) Create a button in html

<button id="ToTopBtn"><i class="fas fa-arrow-up"></i></button>

As you can see the HTML button in the above code but before going further I am telling you to add a “font-awesome” CDN link to add an Icon of an up arrow.

Step 2) Design button with CSS

<style>
#ToTopBtn{
        background-color: red;
        color: white;
        outline: none;
        border: none;
        position: fixed;
        right: 5%;
        bottom: 5%;
        padding: 15px;
        font-size: 20px;
        border-radius: 5px;
        cursor: pointer;
        display: none;
    }
</style>

Add this CSS in your HTML to design button.

Your button will look like this.

Step 3) Now the last step is to Add JavaScript to it

<script>
    const ToTopBtnBtn = document.getElementById("ToTopBtn")
    document.onscroll = function () {
        if (document.documentElement.scrollTop > 20) {
            ToTopBtn.style.display = "block"
        }else{
            ToTopBtn.style.display = "none"
        }
    }
    ToTopBtn.onclick = function(){
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    }
</script>

And your “Back to top Button” has been created now use it your website.

Leave a comment

Website Built with WordPress.com.

Design a site like this with WordPress.com
Get started