0

I'm trying to execute some code when multiple buttons are pushed, I'm trying this as an example but it's not working :

    <script>

    var map = {82: false, 84: false};
    function keydown(e) {
        if (e.keyCode in map) {
            map[e.keyCode] = true;
            if (map[82] && map[84]) {
                alert(" all pressed ");
            }
        }
    }

    function keyup(e)
    {
        if (e.keyCode in map) {
            map[e.keyCode] = false;
        }
    }
    window.addEventListener('keyup', keyup);
    window.addEventListener('keydown', keydown);
    </script>

I get the alert even when only one button is pushed, ( i got it when both are pushed too )

What am i doing wrong please ?

Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36
  • [javascript multiple keys pressed at once](http://stackoverflow.com/a/12444641/3199927) – Tom Feb 26 '15 at 18:28
  • `82` and `84` are `r` and `t` for those wondering – Paul S. Feb 26 '15 at 18:29
  • possible duplicate of [javascript multiple keys pressed at once](http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once) – Ejaz Feb 26 '15 at 18:29

3 Answers3

0

You don't seem to be attaching your keyup handler, so once a key has been pressed it was forever marked as true in your map

window.addEventListener('keyup', keyup);
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Try this:

var map = []; 
onkeydown = onkeyup = function(e){
    e = e || event; // to deal with IE
    map[e.keyCode] = e.type == 'keydown';
    if(map[82] && map[84]){ 
        alert('all pressed');
    }
}

This was also already answered here:

JavaScript multiple keys pressed at once

Please make sure you check to avoid posting a duplicate question.

Community
  • 1
  • 1
0

I think I found the problem, the program doesn't execute the keyup fonction because of the alert, map[82] and map[84] are always true then.

Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36