Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent JavaScript keydown event from being handled multiple times while held down

Tags:

javascript

I have this code:

else if (e.keyCode == 32){       fired = true; 

In a keyDown function (I have added the document.addEventListener code). Now it works just fine, and does exactly what I want it to do. But here's the problem: if you hold down the key, it keeps making fired = true over and over again continuously until it is released. I just want it to set fired = true; once, even if the key is held down.

like image 582
Chris Avatar asked May 22 '11 12:05

Chris


People also ask

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)$/.

How does a user generate multiple Keydown events 1 point?

How does a user generate multiple keydown events? Explanation: If the user holds the key down long enough for it to begin repeating, there will be multiple keydown events before the keyup event arrives. Pressing the key for long time results in multiple calls to the function onkeypress.

What is the difference between Keyup and Keydown in JavaScript?

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

What is the difference between Keydown and keypress events?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.


2 Answers

Edit: It is now fully supported in every browser. except for Internet Explorer

If browser compatibility is not your main concern*, you could try accessing the .repeat property of the KeyboardEvent, as documented here:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat

By doing something like this in your handler function:

function keyDown (e) {   if (e.repeat) { return }    // do stuff here } 

you could avoid the repeated keystrokes.


*: on the MDN site it states that it works in Firefox, and I have successfully used it in Chrome, so the two major browsers should have no problem with it

like image 196
Isti115 Avatar answered Sep 18 '22 09:09

Isti115


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

Then Use onkeyup event

    element.onkeyup = function() {      fired = false;     }; 
like image 31
Vishwanath Dalvi Avatar answered Sep 17 '22 09:09

Vishwanath Dalvi