Create a Scroll to Top Button with JavaScript And CSS


Introduction

Creating a "Scroll to Top" button! This button is a useful feature that allows users to quickly return to the top of a webpage with a single click.

In modern web design, providing users with an easy way to navigate back to the top of a long page can greatly enhance the user experience. A "Scroll to Top" button is a simple yet effective feature that achieves this. In this tutorial, we'll walk you through creating a scroll to top button using HTML, CSS, and JavaScript. Whether you are a beginner or an experienced developer, you will find this guide straightforward and practical.

What is a "Scroll to Top" button?

A "Scroll to Top" button is a UI element that appears on a webpage when the user scrolls down, allowing them to quickly return to the top of the page.

Step 1: Adding the HTML

To start, add a button element to your HTML. This button will serve as the trigger for scrolling back to the top of the page. Insert the following code at the end of your HTML file before closing </body> tag.

HTML
<button id="scrollToTopBtn" class="scroll-to-top" aria-label="Scroll to top">Top</button>

Step 2: Styling with CSS

Next, style your button to make it visible and appealing. Use the following CSS to position the button at the bottom-right corner of the viewport and give it a modern look

CSS
.scroll-to-top {
    display: none;
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 100;
    border: none;
    outline: none;
    background-color: #555;
    color: white;
    cursor: pointer;
    border-radius: 5px;
    padding: 10px 20px;
    font-size: 16px;
    opacity: 0.8;
}
.scroll-to-top::after{
    content: "\25B2";
    margin-left: 5px;
}
.scroll-to-top:hover {
    opacity: 1;
    background-color: #333;
}

Step 3: Adding JavaScript

Now, add functionality to your button using JavaScript. This script will make the button appear when the user scrolls down the page and scroll smoothly back to the top when the button is clicked. Include the following JavaScript in your script file or Insert the end of your HTML file before closing </body> tag.

JavaScript
document.addEventListener("DOMContentLoaded", () => {
    const scrollToTopBtn = document.getElementById("scrollToTopBtn");
    const scrollThreshold = 100;

    // Debounce function to limit how often a function can be executed
    const debounce = (func, wait) => {
        let timeout;
        return (...args) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => func(...args), wait);
        };
    };

    // Toggle visibility of the "Scroll to Top" button based on scroll position
    const toggleScrollToTopBtn = () => {
        const scrollY = window.scrollY || document.documentElement.scrollTop;
        const isVisible = scrollY > scrollThreshold;
        scrollToTopBtn.style.display = isVisible ? "block" : "none";
    };

    // Smoothly scroll to the top of the page
    const scrollToTop = () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth",
        });
    };

    // Debounce the scroll event handler to improve performance
    const handleScroll = debounce(toggleScrollToTopBtn, 100);

    // Add event listeners
    window.addEventListener("scroll", handleScroll, { passive: true });
    scrollToTopBtn.addEventListener("click", scrollToTop);

});

Live preview and edit code your self

Try it Yourself

Benefits of using a "Scroll to Top" button

  • Improves user experience

  • Saves time and effort for users

  • Enhances accessibility

  • Can improve website engagement

  • Encourages Continued Reading

Customization Options

  • Change the button appearance using CSS

  • Add animations or transitions

  • Use different icons or images

  • Customize the button behavior

Conclusion

With these simple steps, you have added a "Scroll to Top" button to your webpage. This feature not only improves navigation but also contributes to a smoother and more user-friendly experience. Feel free to customize the styles and functionality to better suit your site design and needs

Using JQuery With Smooth Scroll Animation

Create a smooth scroll-to-top button using jQuery, you will follow a similar approach to the vanilla JavaScript implementation but leverage jQuery's methods for simplicity.

JQuery
$(document).ready(() => {
    const scrollToTopBtn = $("#scrollToTopBtn");
    const scrollThreshold = 100; // Adjust this value as needed

    // Throttle function to limit the rate at which a function is executed
    const throttle = (func, limit) => {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    };

    // Toggle button visibility based on scroll position
    const toggleScrollToTopBtn = () => {
        if ($(window).scrollTop() > scrollThreshold) {
            scrollToTopBtn.show();
        } else {
            scrollToTopBtn.hide();
        }
    };

    // Scroll to top with smooth behavior
    const scrollToTop = () => {
        $("html, body").animate({
            scrollTop: 0
        }, {
            duration: "slow",
            easing: "swing"
        });
    };

    // Attach throttled scroll event
    $(window).on("scroll", throttle(toggleScrollToTopBtn, 100));

    // Attach click event
    scrollToTopBtn.on("click", scrollToTop);
});

Live preview and edit code

Try it Yourself