Pergunta

So, I've got a Keydown combination working to move between divs in a section of my form, but after using the combination the first time, I can only press the ALT key (Keycode 18) and it runs both if statements in the function, and therefore is calling my other function twice.

It should be checking for the second keydown event before entering the if, or at least that's what I believed.

Is there some Clear command for the keydown I need to do, or a way to reset the listening of the keydown event?

var keys = [];

document.onkeydown = function(evt){    
   var key = evt.keyCode;
   keys[key] = true;
    if(keys[18] && keys[78]){
       NewFocus('#Notes');
       console.log("Notes");
    } 
    if(keys[18] && keys[67]){
        NewFocus('#Callers');
        console.log("Callers");
    }

    return false;
}

function NewFocus(newNav)
    {
        $('.navActive').hide().removeClass('navActive');
            console.log("made it to New Focus event.");
        var id = $(newNav);
            console.log("This is the id " + $(id));
        $(id).show().addClass('navActive');

        return false;;
    }

BTW, I'm running this in Safari and Chrome, and you can see what happens just watching the console.

I must be missing something, but don't know what.

Foi útil?

Solução 2

You need to clear the keys array when the key is released:

document.onkeyup = function (evt) {
    var key = evt.keyCode;
    keys[key] = false;
};

Outras dicas

You need to listen for onkeyup and use delete keys[key] to clear the state of that key.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top