Novak Novak - 1 year ago 134
Javascript Question

How to disable repetitive keydown in JavaScript

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

-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

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

function movFwr() {
if (currPos == 1000) { = 1000 + "px";
} else currPos += 10; = 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 :)

Answer Source

Something like this should do the trick;

var down = false;
document.onkeydown = function () {
    if(down) return;
    down = true;

    // your magic code here

document.onkeyup = function () {
    down = false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download