Javascript onkeydown event fire only once?

There's a "once" parameter you can use

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Eg:

element.addEventListener('keydown', function(event) {  
    doSomething()
}, {once: true});

It'll remove it as soon as it's been called.

Alternatively you can use removeEventListener if it's a named function


I'm surprised it's not mentioned, there's also event.repeat:

document.addEventListener('keydown', (e) => {
  if (e.repeat) return;

  console.log(e.key);
});

This will only fire once per each keypress, since event.repeat turns true after holding the key down.

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#keyboardevent_sequence


Here is a method that uses addEventListener and removeEventListener

var textBox = document.getElementById("textBox");
function oneKeyDown(){
    $("body").append("<h1>KeyDown<h1>"); //just to show the keypress
    textBox.removeEventListener('keydown', oneKeyDown, false);
}
function bindKeyDown(){
  textBox.addEventListener('keydown', oneKeyDown, false);
}
textBox.addEventListener('keyup', bindKeyDown, false)   
bindKeyDown();

Code example on jsfiddle.

One note, for IE you will need to use attachEvent, detachEvent.


You could set a flag:

var fired = false;

element.onkeydown = function() {
    if(!fired) {
        fired = true;
        // do something
    }
};

element.onkeyup = function() {
    fired = false;
};

Or unbind and rebind the event handler (might be better):

function keyHandler() {
     this.onkeydown = null;
     // do something
}

element.onkeydown = keyHandler;

element.onkeyup = function() {
    this.onkeydown = keyHandler;
};

More information about "traditional" event handling.

You might also want to use addEventListener and attachEvent to bind the event handlers. For more information about that, have a look at quirksmode.org - Advanced event registration models.