zaftcoAgeiha zaftcoAgeiha - 27 days ago 16
Javascript Question

Javascript onkeydown event fire only once?

Heylo guys,

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 im new at JS. Also i prefer to avoid using jquery or other libs.
one more thing, this should work for both ie and firefox.

Thanks alot!

Answer

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.