views:

159

answers:

4

Hi,

I'm working on handling the multiple key presses with jQuery.

I have two handlers: 1. keyDownHandler 2. keyUpHandler

keyDownHandler detects if the certain key has been pressed, if yes it sets a certain boolean value to true and carries on with the processing.

keyUpHandler resets the boolean value to false.

All this is required for me to find out if the user has pressed two or three key simultaneously. What I have found is that the keyUpHandler doesn't fire off sometimes and I can't figure out why.

Any ideas?

+1  A: 

try some timeout?

 var my_key = {};
 var timeout = 2000;

    window.onkeydown = function(e)
    {
        e = e||window.event;
        my_key[String.fromCharCode(e.keyCode)] = new Date().getTime();
        special_keys(e);
    }

    window.onkeyup  = function (e)
    {
        e = e||window.event;
        delete my_key[String.fromCharCode(e.keyCode)];
        special_keys(e);
    }

    function special_keys(e)
    {
        my_key["alt"] = e.altKey;
        my_key["ctrl"] = e.ctrlKey;
        my_key["shift"] = e.shiftKey;
    }

    function isPressed(key) {
         return my_key[key] ? (my_key[key] + timeout > new Date().getTime() ): false;
    }
Roki
Hey, thanks for the reply. I have considered using timers, but from what I have seen/heard these can go wrong quite often. My solution ha worked, the problem that I had is that I forgot to register onKeyUp inside the document.ready.
vikp
A: 

Hey, thanks for the reply. I have considered using timers, but from what I have seen/heard these can go wrong quite often. My solution ha worked, the problem that I had is that I forgot to register onKeyUp inside the document.ready.

vikp
A: 

Hey, thanks for the reply. I have considered using timers, but from what I have seen/heard these can go wrong quite often. My solution ha worked, the problem that I had is that I forgot to register onKeyUp inside the document.ready.

vikp
A: 

Pasting a previous answer:

I recommend using this jquery library to write custom handlers for keypresses: http://code.google.com/p/js-hotkeys/

Trying to discern keycodes logically is a nightmare.

Neil McKeown