0

I'm a beginner to JavaScript and animation in general. I recently spent a ridiculous amount of time scouring the internet looking for just a simple basic button-click animation so that a Phonegap app I am working wouldn't look so flat and would react a little bit to the user. I also needed something readable for a beginner like me so I would better understand the idea. I finally came up with something and thought I would share it. Hopefully someone will find this helpful. See code below.

function animateButton(elem, callback) {
  var perc = 0; // Initially radial background is not visible
  var id = setInterval(function() {
    if (perc >= 100) {
      // Change "rgba(194, 194, 194, 1)" to whatever color you want the effect to be
      // Change "rgba(255, 255, 255, 1)" to whatever color the background is
      $(elem).css('background', 'radial-gradient(circle, rgba(194,194,194,1) 0%, rgba(255,255,255,1) 100%)');
      clearInterval(id);
      callback();
    } else {
      $(elem).css('background', 'radial-gradient(circle, rgba(194,194,194,1) 0%, rgba(255,255,255,1) ' + perc + '%)');
      perc = perc + 3;
    }

  }, 1)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div onclick="animateButton(this, () => { alert('Callback')})">Button</div>
Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31

1 Answers1

0

I wouldn't use javascript for animations. Its very ineficient and it sometimes looks buggy as well. Although I don't have a solution for animating the "background" property, what i suggest to you is to take a look at keyframes in css. Those should be the "go to" option when searching for animations : https://www.w3schools.com/css/css3_animations.asp If you cant make it with keyframes, use the "transition" property in css and change the value with javascript. I tried doing this for your example, but transition does not support gradients apparently. I would check this : Use CSS3 transitions with gradient backgrounds

Clauzzz
  • 129
  • 5