Search code examples
javascriptkeyboardalertprompt

KeyboardState.pressed is always true after .prompt or alert - Why?


As the title says, I have tried THREEx and Stemkovskis standalone KeyboardState.js , and neither of them seems to update properly.

This is my code:

m_vKeyboard = new THREEx.KeyboardState();
// m_vKeyboard.update(); // if using stemkovskis
if (m_vKeyboard.pressed("F")) {
    alert("And now it is always true!");
}

you click the F key once, release it; alert window pops up, click OK, it pops up again for all eternity. How come?


Solution

  • Many browsers repeat keydown. Read more here and here (ctrl+f : auto-repeat).

    Here's a proposed solution for your specific problem :

    A. when keydown store its state as true in some array and make it false on keyup.

    wasPressed['F'] = true;  //on keydown
    wasPressed['F'] = false; //on keyup
    

    B. when checking for next keydown check its state as well.

    if (m_vKeyboard.pressed("F") && !wasPressed['F'])
    

    Find full implementation : Here

    UPDATE

    var wasPressed  = {};
    if( keyboard.pressed('F')  && !wasPressed['f'] ){
                alert("F was pressed");
                prompt("Enter data : ");
                wasPressed['f'] = true;         
            }
    

    UPDATE 2

    keyboard.domElement.addEventListener('keydown', function(event){
                wasPressed  = {};
        })