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 :)
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.
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.
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.
The onkeydown attribute fires when the user is pressing a key (on the keyboard).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With