JSFiddle - React, Tailwind, and code Playground

by Colin Soderstrom

HTML

<div class="scroll-gradient"></div>
  <div class="content">
    <!-- Your content goes here -->
  </div>

CSS

.scroll-gradient {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh; /* Full viewport height */
  z-index: -1; /* Place behind other content */
}

.content {
  height: 2000px; /* Just for demonstration purposes to enable scrolling */
}

JavaScript

window.addEventListener('scroll', function() {
  // Get the scroll position as a percentage of the total scrollable height
  const scrollPercent = (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100;

  // Calculate colors based on the scroll position
  const color1 = getColorForScrollPosition(scrollPercent);
  const color2 = getColorForScrollPosition(scrollPercent + 10); // Change as needed for smoothness
  
  // Apply the gradient background to the .scroll-gradient div
  const gradient = `linear-gradient(to right, ${color1}, ${color2})`;
  document.querySelector('.scroll-gradient').style.background = gradient;
});

// Function to get colors based on scroll position
function getColorForScrollPosition(scrollPercent) {
  // Example: Interpolate between red and blue based on scroll position
  const red = 255;
  const blue = 0;
  const green = Math.floor((scrollPercent / 100) * 255);
  return `rgb(${red}, ${green}, ${blue})`;
}