2

How can i get my CSS animation trigger when i press down arrow key?

Animation code:

<head>


  <style>
    body {
  padding: 30px;
}

#down {
  width: 451px;
  height: 589px;
  display: block;
  background-image: url("images/guy.png");
  animation: sprite .6s steps(17) infinite;



}

@keyframes sprite {
 100% {
   background-position: -7667px;
 }
}
  </style>
 </head>

<body>
  <div id=down></div>

  <script src="/js/prefixfree.min.js"></script>
<script>
</script>
</body>

</html>

So i want the css animation to be triggered when i press down. How do i do this?

Javascript moving code

if (40 in keysDown) { // down
        guy.y += guy.speed * modifier;

    }
Asphys
  • 175
  • 3
  • 15
  • You define your animation on `#down.active` (or any other class name you want) instead of `#down` . And you add the class `active` on click. Or toggle it, if you want to stop it on next click. – tao Mar 10 '16 at 08:12
  • @Andrei Gheorghiu I didn't really understand. How can i make it so that it isn't toggled? How can i make the class active only on when i press arrow key down?? – Asphys Mar 10 '16 at 16:41
  • Create a [mcve]. I cannot think of one decent reason why I should create it for you. – tao Mar 10 '16 at 18:06

1 Answers1

0

Here is example fiddle

HTML:

<div id=down></div>

JS:

    $(document).bind("keydown", function(event) {   
   var code = event.keyCode || event.which;
   if(code == 40) { //Down arrow
     //guy.y += guy.speed * modifier;
     $('#down').addClass('down');
   }   
});
$(document).bind("keyup", function(event) {
   //guy.y += guy.speed * modifier;
   $('#down').removeClass('down');
});

CSS:

    .down {
  width: 100px;
  height: 100px;
  display: block;
  border: 1px solid black;
  animation: sprite .6s steps(17) infinite;
}

@keyframes sprite {
 100% {
   background-color: red;
 }
}
Stargazer
  • 478
  • 2
  • 9
  • If i have a javascript background, how can i get the rectangle on top of the background? Also i want it to be so that when i press the button, the animation plays for until i release the button. Not toggle. – Asphys Mar 10 '16 at 15:10