DEV Community

Discussion on: Scroll to top button with JQuery

Collapse
 
peerreynders profile image
peerreynders • Edited

Another stab at vanilla:

Modify:

<button id="topBtn">&#11014;</button>
Enter fullscreen mode Exit fullscreen mode

Modify:

:root {
  --fade-duration: 400ms;
}

#topBtn {
  --fade-duration: 0s;
  position: fixed;
  bottom: 40px;
  right: 40px;
  font-size: 2.5rem;
  width: 50px;
  height: 50px;
  background: #e74c3c;
  color: white;
  border: none;
  cursor: pointer;
  animation-name: fadeOut;
  animation-duration: var(--fade-duration);
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
}

@keyframes fadeOut {
  0% {
    visibility: visible;
    opacity: 1;
  }
  100% {
    visibility: hidden;
    opacity: 0;
  }
}

#topBtn.topBtn {
  animation-name: fadeIn;
  animation-duration: var(--fade-duration);
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
}

@keyframes fadeIn {
  0% {
    visibility: visible;
    opacity: 0;
  }
  100% {
    visibility: visible;
    opacity: 1;
  }
}
Enter fullscreen mode Exit fullscreen mode

Replace:

const BUTTON_ID = 'topBtn';
const DURATION_NAME = '--fade-duration';
const SHOW_BUTTON = 'topBtn';
const SCROLL_DURATION = 300;
const SCROLL_CYCLE = 15;

function initialize(_event) {
  const button = document.getElementById(BUTTON_ID);
  const showButton = (_event) => {
    if (window.scrollY > 40) button.classList.add(SHOW_BUTTON);
    else button.classList.remove(SHOW_BUTTON);
  };

  const scrollTarget = window;
  const scrollToTop = (event) => {
    let y = window.scrollY;
    const x = window.scrollX;
    const step = Math.floor((y * SCROLL_CYCLE) / SCROLL_DURATION);
    const nextStep = () => {
      y = step < y ? y - step : 0;
      window.scrollTo(x, y);
      if (y > 0) {
        setTimeout(nextStep, SCROLL_CYCLE);
        return;
      }
      scrollTarget.focus();
    };

    event.target.blur();
    nextStep();
  };

  // Enable animation after everything is loaded
  const rootStyle = getComputedStyle(document.documentElement);
  const duration = rootStyle.getPropertyValue(DURATION_NAME);
  button.style.setProperty(DURATION_NAME, duration);

  document.addEventListener('scroll', showButton);
  button.addEventListener('click', scrollToTop);
}

if (document.readyState === 'loading')
  document.addEventListener('DOMContentLoaded', initialize);
else initialize();
Enter fullscreen mode Exit fullscreen mode