Search code examples
javascripthtmlcsscss-animationsradial-gradients

Change a button background to a different color by animating a radial gradient


I have a button that, when I select it, I want to add an animated class with a circle that increases in size until the entire background takes on the secondary color. The only problem is that the animation isn't working well, it's crashing. Does anyone know how I can go about solving this problem? Below I leave more or less the method I am using

function change(el){
  el.classList.add('animated')
}
.animated{
  animation: disable 1s linear 1 alternate;
}
@keyframes disable{
  from{
    background: radial-gradient(circle, #00c7be 99%, #4e5d78 100%);
  }
  to{
    background: radial-gradient(circle, #00c7be 0%, #4e5d78 1%);
  }
}
<button onclick="change(this)">
  button
</button>


Solution

  • If I understand what you want to do correctly, I would start by creating an SVG containing a circle with a radial gradient fill.

    <svg viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <radialGradient gradientUnits="userSpaceOnUse" cx="25" cy="25" r="25" id="gradient-0">
          <stop offset="0" style="stop-color: rgb(255, 0, 0);"></stop>
          <stop offset="1" style="stop-color: rgb(128, 128, 255);"></stop>
        </radialGradient>
      </defs>
      <ellipse style="stroke: rgb(0, 0, 0); fill: url(#gradient-0); stroke-width: 0px;" cx="25" cy="25" rx="25" ry="25"></ellipse>
    </svg>
    

    (Note that I’m converting the SVG to PNG for purposes of this answer, because Stack Overflow doesn’t allow SVG uploads.)

    enter image description here

    Then I would use this graphic as the button background, and animate its size from 0% to something large like 800%.

    function change(el){
      el.classList.add('animated')
      setTimeout(() => {
        el.classList.remove('animated')
      }, 4000)
    }
    body {
      font-family: sans-serif;
    }
    button {
      border: 0;
      border-radius: 4px;
      padding: 50px 100px;
      background: #8080ff;
      color: white;
    }
    .animated {
      background-image: url(https://i.sstatic.net/mN3Gi.png);
      background-size: 0%;
      background-repeat: no-repeat;
      background-position: center;
      animation: an1 2s linear 1 forwards;
    }
    @keyframes an1 {
      from {
        background-size: 0%;
      }
      to {
        background-size: 800%;
      }
    }
    <button onclick="change(this)">
      button
    </button>
    <p>Click the button, then wait four seconds, it will reset, and you can try again. If the effect isn't visible the first time you click, try a second and third time. This is not a fault in the code, just a quirk of Stack Snippets.