i want to create a simple event handler for a game, here's my code
$(document).keydown(function(e){
switch(e.keyCode){
case 65: //left (a)
console.log('left');
break;
case 68: //right (d)
console.log('right');
break;
}
});
the problem is that if i press and hold a key, after a little it triggers multiple times. how can i prevent this behaviour? i'm running my code on google chrome
If you've never handled keyboard events in jQuery this is a good place to start. The main keyboard events you need to understand are keydown, keypress, and keyup. In order to handle these events, you must understand what they are and when they'll be triggered.
Definition and Usage. The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).
The order of events related to the keypress event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
Modifier keys Keyboard modifier keys ( ctrl, shift, alt…) will fire keydown () event but not keypress () event. 3. KeyCode – ASCII code For example, A = 65 and a= 97, Please refer to this ASCII table charts. keydown () and keyup () will display a = 65, A = 65 (case insensitive – lowercase and uppercase will display same value).
This is key repeat. You can defeat it if you want to, by remembering that you already know the key is down:
// A map to remember in
var keysdown = {};
// keydown handler
$(document).keydown(function(e){
// Do we already know it's down?
if (keysdown[e.keyCode]) {
// Ignore it
return;
}
// Remember it's down
keysdown[e.keyCode] = true;
// Do our thing
switch(e.keyCode){
case 65: //left (a)
console.log('left');
break;
case 68: //right (d)
console.log('right');
break;
}
});
// keyup handler
$(document).keyup(function(e){
// Remove this key from the map
delete keysdown[e.keyCode];
});
Side note: I think when you're using jQuery, e.which
is the more reliable property, as it's normalized for you by jQuery.
var keyPressed = false;
$(document).on('keydown', function(e) {
var key;
if (keyPressed === false) {
keyPressed = true;
key = String.fromCharCode(e.keyCode);
//this is where you map your key
if (key === 'X') {
console.log(key);
//or some other code
}
}
$(this).on('keyup', function() {
if (keyPressed === true) {
keyPressed = false;
console.log('Key no longer held down');
//or some other code
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With