DEV Community

Discussion on: How to create a scroll to top button with vanilla JS & CSS

Collapse
 
lexlohr profile image
Alex Lohr

Nice one. An interesting yet mostly unknown property of classList is that classList.toggle accepts a second argument to force a toggle state, so your code can be reduced:

// Before
if ((rootElement.scrollTop / scrollTotal) > 0.25) {
    // Show the button
    scrollToTopBtn.classList.add("isVisible")
} else {
    // Hide the button
    scrollToTopBtn.classList.remove("isVisible")
}

// After
scrollToTopBtn.classList.toggle(
  "isVisible",
  (rootElement.scrollTop / scrollTotal) > 0.25
)
Enter fullscreen mode Exit fullscreen mode