var scrollToTopBtn = document.querySelector(".scrollToTopBtn") var rootElement = document.documentElement function handleScroll() { // Do something on scroll var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight if ((rootElement.scrollTop / scrollTotal ) > 0.0) { 8 // Show button scrollToTopBtn.classList.add("showBtn") } else { // Hide button scrollToTopBtn.classList.remove("showBtn") } } function scrollToTop() { // Scroll to top logic rootElement.scrollTo({ top: 0, behavior: "smooth" }) } scrollToTopBtn.addEventListener("click", scrollToTop)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter