|
[Javascript] Multiple Keypresses |
Jeff Bernard
Member #6,698
December 2005
|
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). -- |
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. ____________________________________________________________________________________________ |
Jeff Bernard
Member #6,698
December 2005
|
Hmmm... I suppose I can. Here's a little hack I put together that appears to work fine. 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. -- |
bamccaig
Member #7,536
July 2006
|
There are keydown and keyup events. So in theory, you could tie them into some state object or something. 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 -- acc.js | al4anim - Allegro 4 Animation library | Allegro 5 VS/NuGet Guide | Allegro.cc Mockup | Allegro.cc <code> Tag | Allegro 4 Timer Example (w/ Semaphores) | Allegro 5 "Winpkg" (MSVC readme) | Bambot | Blog | C++ STL Container Flowchart | Castopulence Software | Check Return Values | Derail? | Is This A Discussion? Flow Chart | Filesystem Hierarchy Standard | Clean Code Talks - Global State and Singletons | How To Use Header Files | GNU/Linux (Debian, Fedora, Gentoo) | rot (rot13, rot47, rotN) | Streaming |
|