730
730

Reputation: 21

document.onkeydown not working, or working just once

So I have the following:

document.onkeydown = function(e) {
    e = e || window.event;
    if (e.keyCode == 119) {
        if (currentMode == 3) {
            currentMode = 0;
        } else {
            currentMode = currentMode++;
        }
        switchMode(currentMode);
    }
};

I've tried several combinations of document, body and press/down/up, and none seem to work. What's worse, the code (not this one, but a previous iteration) worked, until I removed a certain element. Now it either runs once then doesn't detect the keypresses anymore, or the keypresses are never even recognized to begin with.

I'll edit in a Fiddle with the whole page if necessary.

Upvotes: 0

Views: 1004

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

It is not a correct increment:

currentMode = currentMode++;

Your currentMode will never increase, because it will assign the same value.

Change it to:

currentMode++;

And it will work (keyCode 119 is F8):

var currentMode = 0;

document.onkeydown = function(e) {
    e = e || window.event;
    if (e.keyCode == 119) {
        if (currentMode == 3) {
            currentMode = 0;
        } else {
            currentMode++;
        }
        switchMode(currentMode);
    }
};

function switchMode(mode) {
    document.getElementById('mode').innerText = mode;
}
Current mode: <span id="mode">0</span>

Upvotes: 1

Related Questions