top of page arrow
Background Gradient Animation

Animate a background gradient change on a specific div or element once the button is clicked. The colors appearing in the gradients will display during the animation (and when it is stopped) for easy capture.


The Gradient Colors

Colors Used: COLOR1, COLOR2, COLOR3

The HTML

<main>
<button>Change Background Gradient</button>
<main>

Simple, right? Style it to suit.

The Javascript

First, define the button and the element we want to target. In this case, we will change the background of the "main" element.

  const button = document.querySelector("button");
  const targetMain = document.querySelector("main");

Next, define the function to change the background.

  const changeBackground = () => {

Prevent the function from running multiple times and overlapping itself if the button has already been clicked.

  if (intervalId) {
  return;
  }

Generate three random hex colors for the gradient, converting the generated number to a string in base 16 hexadecimal using the toString method and assigning this string to a const variable named 'hexVal'. Then the hexVal variable values look something like this: 'c2078a', 'bb007d', '660066'.

  const hexColor1 = Math.floor(Math.random() * 0xffffff).toString(16);
  const hexColor2 = Math.floor(Math.random() * 0xffffff).toString(16);
  const hexColor3 = Math.floor(Math.random() * 0xffffff).toString(16);

Set the linear gradient as the background by putting a hashtag on the front of the hexVal variables, turning them into color values the browser can understand.

  targetMain.style.background = `linear-gradient(to right, #${hexColor1}, #${hexColor2}, #${hexColor3})`;

Add a little timer and make it change every two seconds once the button is clicked. Change the interval in microseconds to suit your preferences.

  setLinearGradientBackground();
  intervalId = setInterval(setLinearGradientBackground, 2000);   }

Finally, make it work when the button is clicked.

  button.addEventListener("click", changeBackground);

When you inspect the code for this page, you will see that I have added "start" and "stop" buttons, but you can stop the animation after a set period of time instead, if you prefer.

  setTimeout(() => {
  clearInterval(intervalId);
  }, 10000);

I don't prefer. Let it go forever!

11/12/2023