How to Create a Scroll Back to Top Button with CSS and JavaScript

Introduction

A "Scroll Back to Top" button allows users to quickly return to the top of a long webpage with a single click. It’s a common UX feature, especially on content-heavy sites. You can create this button using a combination of HTML, CSS for styling, and JavaScript to handle the scroll behavior.

In this tutorial, you'll learn how to create a scroll-back-to-top button that appears when the user scrolls down and smoothly returns to the top when clicked.

Problem Statement

Create a "Back to Top" button that:

  • Stays hidden until the user scrolls down a certain distance.
  • Smoothly scrolls the page back to the top when clicked.

Example:

  • Input: The user scrolls down the page and clicks the "Back to Top" button.
  • Output: The page smoothly scrolls back to the top.

Solution Steps

  1. Use HTML to Create the Button: Define the back-to-top button in HTML.
  2. Style the Button with CSS: Style the button so it’s fixed at the bottom right of the page and only visible after scrolling.
  3. Use JavaScript for Interactivity: Add JavaScript to show the button when the user scrolls down and handle the smooth scrolling effect when clicked.

HTML, CSS, and JavaScript Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Back to Top Button</title>
    <style>
        /* Step 1: Style the back to top button */
        .back-to-top {
            position: fixed;
            bottom: 20px;
            right: 20px;
            display: none; /* Hidden by default */
            width: 50px;
            height: 50px;
            background-color: #3498db;
            color: white;
            font-size: 24px;
            border: none;
            border-radius: 50%;
            text-align: center;
            line-height: 50px;
            cursor: pointer;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            transition: opacity 0.3s ease, transform 0.3s ease;
        }

        /* Step 2: Hover effect for the button */
        .back-to-top:hover {
            background-color: #2980b9;
            transform: translateY(-3px); /* Slight lift on hover */
        }

        /* Step 3: Show the button when needed */
        .back-to-top.show {
            display: block;
            opacity: 1;
        }
    </style>
</head>
<body>

    <!-- Content to scroll -->
    <div style="height: 1500px; padding: 20px;">
        <h1>Scroll Down</h1>
        <p>Keep scrolling to see the "Back to Top" button appear!</p>
    </div>

    <!-- Back to Top button -->
    <button class="back-to-top" id="backToTopBtn">&#8679;</button>

    <!-- Step 4: JavaScript to handle scroll and click behavior -->
    <script>
        // Get the button
        const backToTopBtn = document.getElementById("backToTopBtn");

        // Show the button when the user scrolls down 300px from the top
        window.onscroll = function() {
            if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
                backToTopBtn.classList.add("show");
            } else {
                backToTopBtn.classList.remove("show");
            }
        };

        // Scroll back to the top when the button is clicked
        backToTopBtn.addEventListener("click", function() {
            window.scrollTo({
                top: 0,
                behavior: "smooth" // Smooth scrolling
            });
        });
    </script>

</body>
</html>

Output

You can play with the above HTML in Online HTML Editor and Compiler. Here is the output of the above HTML page.:

Explanation

Step 1: Style the Back to Top Button

The .back-to-top class styles the button to be fixed at the bottom right corner of the page. It’s initially hidden with display: none and has a circular shape, with a box-shadow for depth and smooth transitions for hover effects.

.back-to-top {
    position: fixed; /* Stays in the same position while scrolling */
    bottom: 20px; /* Distance from the bottom of the page */
    right: 20px; /* Distance from the right side of the page */
    display: none; /* Initially hidden */
    width: 50px; /* Circular button */
    height: 50px;
    background-color: #3498db; /* Blue background */
    color: white; /* White arrow icon */
    font-size: 24px; /* Arrow size */
    border: none;
    border-radius: 50%; /* Circular shape */
    text-align: center; /* Center the arrow */
    line-height: 50px; /* Center vertically */
    cursor: pointer; /* Pointer cursor */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Adds shadow for depth */
    transition: opacity 0.3s ease, transform 0.3s ease; /* Smooth transitions */
}

Step 2: Hover Effect for the Button

When the user hovers over the button, the background color darkens, and the button lifts slightly to indicate it’s clickable.

.back-to-top:hover {
    background-color: #2980b9; /* Darker blue on hover */
    transform: translateY(-3px); /* Slight lift effect */
}

Step 3: Show the Button When Needed

The .show class is added dynamically with JavaScript when the user scrolls down more than 300px. This class makes the button visible by setting display: block.

.back-to-top.show {
    display: block; /* Show the button */
    opacity: 1;
}

Step 4: JavaScript for Scroll and Click Behavior

JavaScript is used to:

  1. Show the button when scrolling: The window.onscroll event checks how far the user has scrolled. If the user scrolls more than 300px, the button appears.
  2. Smooth scroll back to top: When the user clicks the button, the page scrolls smoothly back to the top using the window.scrollTo() method with behavior: "smooth".
// Show the button when the user scrolls down 300px from the top
window.onscroll = function() {
    if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
        backToTopBtn.classList.add("show");
    } else {
        backToTopBtn.classList.remove("show");
    }
};

// Scroll back to the top when the button is clicked
backToTopBtn.addEventListener("click", function() {
    window.scrollTo({
        top: 0,
        behavior: "smooth" // Smooth scrolling
    });
});
  • window.scrollTo(): Scrolls the page to the top with a smooth behavior.
  • backToTopBtn.classList.add("show"): Shows the button when the user scrolls down.
  • backToTopBtn.classList.remove("show"): Hides the button when the user scrolls back up.

Customization

Change Button Size

To make the button larger or smaller, adjust the width, height, and line-height values:

.back-to-top {
    width: 60px;
    height: 60px;
    line-height: 60px;
}

Change Button Color

You can customize the button's background and hover colors:

.back-to-top {
    background-color: #e74c3c; /* Red background */
}

.back-to-top:hover {
    background-color: #c0392b; /* Darker red on hover */
}

Change the Scroll Distance to Show the Button

In the JavaScript code, modify the 300 value to make the button appear sooner or later, depending on how far the user scrolls:

if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
    backToTopBtn.classList.add("show");
}

Add Icon Instead of Text

You can replace the text arrow (&#8679;) with an icon from Font Awesome or another icon library:

<button class="back-to-top" id="backToTopBtn">
    <i class="fas fa-arrow-up"></i>
</button>

Make sure to include the Font Awesome CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>

Conclusion

Creating a "Scroll Back to Top" button using HTML, CSS, and JavaScript is a simple and effective way to improve user navigation on long web pages. By combining CSS for styling and JavaScript for interactivity, you can make a dynamic button that enhances the user experience with smooth scrolling and responsive behavior.

Comments