Simple way to create a scroll to top button

Simple way to create a scroll to top button

In this tutorial, I will show you how to create a simple and smooth Scroll to Top button for a web page using HTML, CSS, and pure JavaScript.

Scroll to top of the page button

<div class="scroll-top" id="scrollTopBtn"><span>🠕</span></div>

html {
  scroll-behavior: smooth;
}

.scroll-top {
  display: none;
  position: fixed;
  bottom: 50px;
  right: 30px;
  z-index: 9999;
}

.scroll-top span {
  display: flex;
  width: 50px;
  height: 50px;
  border: 2px solid #222222;
  border-radius: 5px;
  justify-content: center;
  align-items: center;
  font-size: 32px;
  cursor: pointer;
}

.scroll-top span:hover {
  color: white;
  background-color: rgba(0, 0, 0, 0.9);
}

var scrollTopBtn = document.getElementById("scrollTopBtn");

function onScroll() {
    if (document.documentElement.scrollTop > 500) {
        scrollTopBtn.style.display = "block";
    } else {
        scrollTopBtn.style.display = "none";
    }
}

window.addEventListener("scroll", onScroll);

scrollTopBtn.addEventListener("click", function () {
    document.documentElement.scrollTop = 0;
});

The if condition inside the onScroll() function checks that if a user scrolls down 500px from the top of the document then show the scroll-to-top button.