0

I have a flashing sprite css animation for an empty div.

#flashIt{
 width: 50%;
 height: 100px;
 background: blue;
 margin: 10px auto;
 border: solid 2px black;
 left: 25%;
 animation: flash 1s linear infinite;
} 
@keyframes flash {
  0% { opacity: 1; }
  50% { opacity: .1 }
  100% { opacity: 1; } 
 }
 

So this animation works as it is. However I want the animation to begin when a key is pressed by the user on their keyboard. How can I do this using JS? Help on this would be much appreciated. Thanks

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

2 Answers2

0

A simple way to do this would be to listen for a keypress and then, when a key is pressed, apply a class to the appropriate DOM element. This class would contain your animation styling which would then animate the element just like you want.

var elementToAnimate = document.findElementById("flashIt");
document.addEventListener('keypress', function(event) {
  elementToAnimate.classList.add('your-animation-class');
});
Luke Glazebrook
  • 580
  • 2
  • 14
-2

Here is an example of what you could do.

$(document).keypress('keypress',function(e){
      if(e.which==13){
         $('div').toggleClass('animation');
     }
 });

This will activate the animation class when you press the enter key.

Swink
  • 353
  • 3
  • 26