Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » [Javascript] Multiple Keypresses

Credits go to Timorg for helping out!
This thread is locked; no one can reply to it. rss feed Print
[Javascript] Multiple Keypresses
Jeff Bernard
Member #6,698
December 2005
avatar

So, you can do something like this to grab keypresses in Javascript:

window.addEventListener("keydown", function(e)
{
   if (e.keyCode == 13) // enter key
   if (e.keyCode == //other keys
}

But this only seems to let me capture one keypress at a time (ie- I can't set it up for user is pressing both UP key and LEFT key, it'll attach to whatever the last pressed key was).

I'm thinking of playing around with HTML5's <canvas> element by making a game in the browser, and it would be very useful to be able to detect if more than one key is pressed at a time (if it's possible).

--
I thought I was wrong once, but I was mistaken.

Timorg
Member #2,028
March 2002

Can you set a variable that the key is down, and unset it when its released? Kind of like allegro 4.2's key array.

____________________________________________________________________________________________
"c is much better than c++ if you don't need OOP simply because it's smaller and requires less load time." - alethiophile
OMG my sides are hurting from laughing so hard... :D

Jeff Bernard
Member #6,698
December 2005
avatar

Hmmm... I suppose I can. Here's a little hack I put together that appears to work fine.

#SelectExpand
1var down = []; 2window.addEventListener("keydown", function(e) 3{ 4 var contains = false; 5 for (var i = 0; i < down.length; i++) 6 if (down[i] == e.keyCode) 7 { 8 contains = true; 9 break; 10 } 11 if (!contains) 12 { 13 down.push(e.keyCode) 14 } 15} 16 17window.addEventListener("keyup", function(e) 18{ 19 var i = down.indexOf(e.keyCode); 20 if (i != -1) 21 down.splice(i, 1); 22});

This wasn't obvious to me first since it actually runs the "keydown" event for as many keys that get pressed instead of detecting all the presses at once, but it should work. Thanks.

--
I thought I was wrong once, but I was mistaken.

bamccaig
Member #7,536
July 2006
avatar

There are keydown and keyup events. So in theory, you could tie them into some state object or something.

#SelectExpand
1var my_key = {}; 2 3function keydown_handler(e) 4{ 5 my_key[String.fromCharCode(e.keyCode)] = true; 6 special_keys(e); 7} 8 9function keyup_handler(e) 10{ 11 my_key[String.fromCharCode(e.keyCode)] = false; 12 special_keys(e); 13} 14 15function special_keys(e) 16{ 17 my_key["alt"] = e.altKey; 18 my_key["ctrl"] = e.ctrlKey; 19 my_key["shift"] = e.shiftKey; 20} 21 22window.addEventListener("keydown", keydown_handler, false); 23window.addEventListener("keyup", keyup_handler, false);

** EDIT **

/beaten :-[

Go to: