Back To Top Button JS

This vanilla JavaScript snippet that allows you to smoothly scroll back to the top of a page when triggered. Copy and paste code inside code block or you can enter in custom code field from setting.

Set your button id to “#scroll-top”.

<script>
// Function to smoothly scroll back to the top
function scrollToTop() {
  const scrollDuration = 1000; // Duration of the scroll animation in milliseconds
  const scrollStep = -window.scrollY / (scrollDuration / 15);
  
  const scrollInterval = setInterval(() => {
    if (window.scrollY !== 0) {
      window.scrollBy(0, scrollStep);
    } else {
      clearInterval(scrollInterval);
    }
  }, 15);
}

// Usage example: Attach the scrollToTop function to a button or any other trigger
const scrollToTopButton = document.getElementById('scroll-top');
scrollToTopButton.addEventListener('click', scrollToTop);
</script>

Leave comment or code correction