-1

I have an animation that should start on keydown for a set duration (3s or so).

Wondering if I can bind the animation function to jquery keydown but how can I add the duration to that or if there is another jquery plugin that can handle this?

The animation is something like:

$('.slide1').slideUp();

but I need to bind this to a key-hold event so it is triggered when someone holds down the spacebar for 3s. I have no idea where to even begin here.

Something like - but how to trigger with the actual spacebar?

$('spacebar').keydown(
  $('.slide1').slideUp();
), 3000) ? 
njpatten
  • 165
  • 1
  • 3
  • 15
  • Well we have no idea how you are running the animation to start. – epascarello Sep 07 '16 at 13:40
  • You want the animation to last for 3 seconds, or you want it triggered when the key is held down for three seconds? Your question isn't clear. Some information about what you've tried already would help a lot too – Rory McCrossan Sep 07 '16 at 13:41
  • You'd have to set a global timer on keydown and then stop it on keyup to see the length of time it was held down – Pete Sep 07 '16 at 13:42
  • Do you have a fiddle? It's good to know about your scenario and what you're waiting from that to help you – RPichioli Sep 07 '16 at 13:44

1 Answers1

0
$(window).keypress(function (e) {
  if (e.keyCode === 0 || e.keyCode === 32) {
    e.preventDefault()
    console.log('Space pressed')
    //do some stuff here
    /*some animation*/.delay(3000);//plays animation for 3 seconds
  }
});

As others have commented, it is hard to see what you are looking for specifically without any example code. However it sounds like you are looking for something like this.

Mike
  • 632
  • 7
  • 22
  • This is exactly what I'm looking for except I need to add a duration to the spacebar hold. If they just hit the spacebar nothing happens but the event is triggered if they hold it for 3 seconds. Is this possible? – njpatten Sep 07 '16 at 14:13
  • 1
    ahhh, then you will want something along the lines of $(window).keydown(function (e) {.......... Just remove the delays, everytime the OS sends a key signal, it should fire the key down event and execute your loop. In other words, do what you want to do while the key is pressed. I would suggest looking into this library though: https://p5js.org/ It is a good simple library meant for data representation/simple animations/simple games and other things as well as having a host of key detection handlers built right into it – Mike Sep 07 '16 at 14:16