Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onkeydown event fire only once?

Tags:

I want to have a onkeydown event fire a function only once. for that function to fire again, the user has to release the key and press/hold again. I know its fairly simple but I'm new at JS. Also I prefer to avoid using jQuery or other libs. One more thing, this should work for both ie and firefox.

like image 969
WindowsMaker Avatar asked Mar 18 '11 14:03

WindowsMaker


People also ask

What is the event for Onkeydown?

The onkeydown event occurs when the user is pressing a key (on the keyboard).

What is the use of Onkeydown event in JavaScript?

The onkeydown attribute fires when the user is pressing a key (on the keyboard).

What is the difference between Onkeyup and Onkeydown?

The onKeyDown event is triggered when the user presses a key. The onKeyUp event is triggered when the user releases a key.

How do I stop Keydown event?

To cancel keydown with JavaScript, we can call preventDefault in the keydown event handler. For instance, we write: document. onkeydown = (evt) => { const cancelKeypress = /^(13|32|37|38|39|40)$/.


2 Answers

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.

like image 59
Felix Kling Avatar answered Oct 11 '22 23:10

Felix Kling


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

document.addEventListener('keydown', (e) => {
  if (!e.repeat)
    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

like image 32
karmaral Avatar answered Oct 12 '22 00:10

karmaral