Force keydown event to fire only once on keyCode

The situation . I have a handler keydownwith switchfor which key is pressed, fairly standard material, but when a key is held, the event keydownfires repeatedly (more than once, when the key is pressed).

Why is this a problem . I want the active listener to keydownbe active, i.e. could detect several keystrokes of one key at once, but it has only fire events once per keydown. I want to do something on keyupthis keyCodebased on the time between decrease and increase, but this time is twisted due to the many triggers.

What I tried : I am currently saving a list keyCodesthat do not work, and checking them in a handler keydownso that the default behavior does not occur if it is keyCodeon my list. Nevertheless, the event is still very often triggered, and I am concerned about the effectiveness / elegance of this solution.

Actual question : is there a good way to limit the triggering of an event keydownonly when the key is physically pressed down or only for listening to certain key codes?

+5
source share
3 answers

In the keydown handler, verify that the key matches the last processed key. If so, get out early. On the keyboard, forget about the last processed key.

For instance:

var lastEvent;
var heldKeys = {};

window.onkeydown = function(event) {
    if (lastEvent && lastEvent.keyCode == event.keyCode) {
        return;
    }
    lastEvent = event;
    heldKeys[event.keyCode] = true;
};

window.onkeyup = function(event) {
    lastEvent = null;
    delete heldKeys[event.keyCode];
};​

( "" ).

+8

, . true . , , false. , ( ). key-up, . , , true ( ), "" .

0

, , , : jsFiddle

CTRL + B , . , . , .

0

All Articles