Javascript onkeydown fire event only once?

Heylo guys

I want the onkeydown event to fire the function only once. for this function to work again, the user must release the key and press / hold again. I know its pretty simple, but im new to JS. I also prefer to avoid using jquery or other libraries. one more thing, this should work for both ie and firefox.

Thanks a lot!

+6
javascript javascript-events
source share
5 answers

You can set the flag:

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

Or untie and recheck the event handler (maybe better):

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

Additional information on "traditional" event handling.

You can also use addEventListener and attachEvent to bind event handlers. For more information about this, see quirksmode.org - Advanced Event Logging Models .

+14
source share

Here you go:

 test.onkeydown = function() { if ( this.className === 'hold' ) { return false; } this.className = 'hold'; // call your function here }; test.onkeyup = function() { this.className = ''; }; 

Live demo: http://jsfiddle.net/simevidas/xAReL/2/

+2
source share

JQuery one will help you.

What it does is bind eventHandler to the event, and when the event occurs, it fires eventHandler and unties it so that it does not fire on the next event.

0
source share

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(); 

Sample jsfiddle code.

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

0
source share

as indicated in other answers, there is no “onkeyfirstdown" or similar event to listen to.

the best solution is to keep track of which keys are already in the js object:

 var keysdown = {}; element.addEventListener('keydown', function(evt) { if(!(evt.key in keysdown)) { keysdown[evt.key] = true; // key first pressed } }); element.addEventListener('keyup', function(evt) { delete keysdown[evt.key]; }); 

thus, you will not miss keyfirstpressed events if more than one key is held.

(many other solutions posted here will only work when other keys are not omitted).

0
source share

All Articles