Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable repetitive keydown in JavaScript [duplicate]

I have a same problem like this guy How to disable repetitive keydown in jQuery , it's just that I'm not using jQuery so I'm having hard time translating it to "pure" JavaScript, anyways I have set switch-case of some keys and when I press and hold right arrow key my div is flying. Also if it's not a problem can you tell me what would be the easiest way to stop div movement when I let the right arrow key go, do I have to make a new switch case with clearInterval or?

switch (keyPressed) {
    case 39:
        setInterval(movFwr, 50);
        break;
}

function movFwr() {
    if (currPos == 1000) {
        a.style.left = 1000 + "px";
    } else currPos += 10;
    a.style.left = trenutnaPozicija + "px";
}

I'm sorry guys, I've been busy a bit, I'm testing all possibilities and so far I have seen some interesting suggestions. I'll test em all these days and then rate of what ever is that you do on this site. Great community I must say. Thank you all for your help :)

like image 462
Novak Avatar asked Jul 07 '13 18:07

Novak


People also ask

What is the difference between keypress () and Keydown ()?

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.

What is the difference between KeyUp and Keydown in Javascript?

Occur in sequence when a user presses and releases a key. KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

What is the return value of Keydown function?

Return values: It returns whether any key is pressed or not or which key is pressed. jQuery code to show the working of keydown() Method: Code #1: Below code is used to check if a key is on its way down.

What is on Keydown?

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


1 Answers

Something like this should do the trick;

var down = false;
document.addEventListener('keydown', function () {
    if(down) return;
    down = true;

    // your magic code here
}, false);

document.addEventListener('keyup', function () {
    down = false;
}, false);
like image 52
yckart Avatar answered Oct 21 '22 11:10

yckart