0 points

Scroll - to - Top Button with Vanilla JS - Detecting the scroll position


dashboard

Wed Oct 28 2020 08:52:54 GMT+0000 (UTC)

Posted by @julien #javascript

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)
content_copy Copy

https://codepen.io/marcelrojas/pen/GRZOWwp