DEV Community

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

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

A few years ago I realized it as a plugin in vanilla.js

insert the following line before the closing body tag:

<script data-color=blue src="scrolltotop.js"></script>

The file scrolltotop.js:

(function(){
  const scrollScript = document.currentScript,
        scrollButtonColor = scrollScript.dataset.color || 'red',
        fhwScrollerDiv = document.createElement( 'div' ),
        scrollMe = () => {
          if ( document.querySelector( 'body' ).scrollIntoView ){
            document.querySelector( 'body' )
              .scrollIntoView( { behavior: 'smooth' } )
          } else {
          //Polyfill for scrollIntoView....
            let diff = document.documentElement.scrollTop || document.body.scrollTop;
            if (diff > 0) {
              window.requestAnimationFrame(scrollMe);
              window.scrollTo(0, diff - diff / 6);
            }
          }
        }

  fhwScrollerDiv.innerHTML = `
    <svg width="50" height="50" viewbox="0 0 100 100">
      <circle  
        fill="${scrollButtonColor}" 
        cx="50" 
        cy="50" 
        r="50" 
      />
      <path 
        stroke="white" 
        stroke-width="16" 
        stroke-linecap="round" 
        d="M50 80 L50 20 M50 20 L80 50 M50 20 L20 50"
      />
      </svg>`;

  fhwScrollerDiv.style.cssText=`
    z-index:1000;
    position:fixed;
    bottom:20px;
    right:10px;
    cursor:pointer;
    display:none;`

  document.body.appendChild(fhwScrollerDiv);

  window.onscroll = function() {
      if (this.pageYOffset > 200) {
        fhwScrollerDiv.style.opacity = "0.5";
        fhwScrollerDiv.style.display = "block";
      } else {
        fhwScrollerDiv.style.opacity = "0";
        fhwScrollerDiv.style.display = "none";
      }
  }

  fhwScrollerDiv.querySelector('svg')
    .onmouseover = () => 
      fhwScrollerDiv.style.opacity = "1"

  fhwScrollerDiv.querySelector('svg')
    .onmouseout = () => 
      fhwScrollerDiv.style.opacity = "0.5"

  fhwScrollerDiv.onclick = scrollMe;  
})();  
Enter fullscreen mode Exit fullscreen mode