25% off ProSNIPC25OFF

Back-to-Top Button

Adds a smooth-scroll back-to-top button that appears after the user scrolls down the page.

Module3 parts · by SnipCraft

PHPEnqueue

php
<?php
if ( ! function_exists( 'scseed_back_to_top_output' ) ) {
    function scseed_back_to_top_output() {
        echo '<button id="scseed-back-top" aria-label="' . esc_attr__( 'Back to top', 'scseed' ) . '" style="display:none">' .
             '&#8679;</button>';
    }
    add_action( 'wp_footer', 'scseed_back_to_top_output' );
}

CSSStyles

css
#scseed-back-top {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  z-index: 9999;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: #0073aa;
  color: #fff;
  border: none;
  font-size: 1.4rem;
  line-height: 44px;
  text-align: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease, transform 0.3s ease;
  padding: 0;
}
#scseed-back-top.visible {
  opacity: 1;
}
#scseed-back-top:hover {
  background: #005177;
  transform: translateY(-3px);
}

JavaScriptScript

js
(function () {
  'use strict';
  var btn = document.getElementById('scseed-back-top');
  if (!btn) { return; }

  function onScroll() {
    if (window.scrollY > 300) {
      btn.style.display = 'block';
      btn.classList.add('visible');
    } else {
      btn.classList.remove('visible');
      setTimeout(function () {
        if (!btn.classList.contains('visible')) {
          btn.style.display = 'none';
        }
      }, 300);
    }
  }

  window.addEventListener('scroll', onScroll, { passive: true });

  btn.addEventListener('click', function () {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  });
})();
#frontend#ux#navigation#accessibility