Javascript 3-Key Maximum with .onkeydown/up Keypress Detection

When I detect keys being pressed with JavaScript in Mozilla Firefox 22, I am unable to detect any more than 3 keys being pressed when using document.onkeydown and document.onkeyup, setting each key to either true or false. My code is:

document.onkeydown = checkKey;
document.onkeyup = checkKeyUp;

function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == 87 || e.keyCode == 38) keyW = true
    if (e.keyCode == 65 || e.keyCode == 37) keyA = true
    if (e.keyCode == 83 || e.keyCode == 40) keyS = true
    if (e.keyCode == 68 || e.keyCode == 39) keyD = true
}

function checkKeyUp(e) {
    e = e || window.event;
    if (e.keyCode == 87 || e.keyCode == 38) keyW = false
    if (e.keyCode == 65 || e.keyCode == 37) keyA = false
    if (e.keyCode == 83 || e.keyCode == 40) keyS = false
    if (e.keyCode == 68 || e.keyCode == 39) keyD = false
}

keyW = false
keyA = false
keyS = false
keyD = false

But all four of the keys cannot be all set to true at the same time by pressing them. There will always be one last one that is false and stays that way whether or not it is pressed.

This is because a web browser would not need to detect more than 3 keys at a time ([Ctrl]+[Shift]+[+] for example).

Here is an experiment I made:

http://jsfiddle.net/n5vbm/

Is there a way to get around this?

Answers:

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.