Mike Hordecki
Mike Hordecki

Reputation: 97121

Capturing distinct keypresses

When you hold down a key, the JQuery events start to pop out like crazy for this single key press:

...
keydown
keypress
keyup
keydown
keypress
keyup
...

Is there any (even non-browser-portable) way to capture only one event for each key pressed (example: press A and hold it down, and this should yield only one function call)?

Cheers!

Upvotes: 1

Views: 741

Answers (2)

xtofl
xtofl

Reputation: 41509

Since you're giving jQuery a callback, you're surrendering to it's wits. However, you could introduce some more latency for excessive notifications by installing some sort of lazy event queue that you process every tenth of a second.

queue = new Array();
setTimeInterval( 100, function() { queue.process(); } );

queue.process = function( ) { 
    key = queue[0];
    process( key );

    // consume equivalent keypresses by shifting array
    var originallength = queue.length;

    // find shift size
    var firstdiff = 1;
    for(; firstdiff < queue.length && queue[ firstdiff ] == key; 
          firstdiff=firstdiff+1 ) 
    {}
    var newlength = originallength - firstdiff;

    // shift everything and delete trailing tail
    var i = firstdiff;        
    for( var j = 0; j != newlength; j=j+1 ) { queue[ j ] = queue[ j+firstdiff ]; }
    for( var k = newlength; k != originallength; k=k+1 ) { queue[k]=null; }
}

$(document).keyup( function(e) { queue[ queue.length ] = e; } );

Or prevent appending to the queue alltogether using a minimal time diff between keypress events, as in this answer.

Upvotes: 2

Josh Stodola
Josh Stodola

Reputation: 82483

I have found that keyup works the best...

$(document).keyup(function(e) {
  alert(e.keyCode);
});

Upvotes: 5

Related Questions