user2108135 user2108135 - 14 days ago 6
Javascript Question

Multiple keypress function jquery

i am complete newbie in jquery/js

I am trying to create web interface for my robotcar and check for multiple keypresses, whenever i release all keys robotcar would stop.

http://jsfiddle.net/gFcuU/1105/

var keys = {};

$(document).keydown(function (e) {
keys[e.which] = true;
keypr();
printKeys();
});

$(document).keyup(function (e) {
delete keys[e.which];
printKeys();
});

function printKeys() {
var html = '';
for (var i in keys) {
if (!keys.hasOwnProperty(i)) continue;
html += '<p>' + i + '</p>';
}
$('#out').html(html);
}

function keypr(){
if (keys[87] && keys[68] == true){
alert('shit works');
}
}


Multiple keypress detection works but if i press W+D stated in function keypr it stops working properly.
Thanks for help

Answer

Dude. Your code is working perfectly, but when you do the alert while detecting keypresses, it gets stuck.

Just remove the alert and everything is gonna be fine. if you don't wanna remove the alert i guess you have to remove the object, before displaying the alert.

function keypr(){
    if (keys[87] && keys[68] == true){
      delete keys[68];
      delete keys[87];
      alert('shit works');
  }