njpatten njpatten - 3 months ago 9
jQuery Question

trigger event with spacebar keydown for set duration

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) ?

Answer
$(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.