Returns true if the key in the javascript loop is missing?

I want to add a condition inside the loop that checks if the right arrow is pressed, and if it moves the div a little to the right. However, I do not know how to check how they work.

I use the code for this, but it is very long, and I'm sure there is a shorter way to do this.

This is the code:

<div id="char"></div> <script> setInterval(function() { // here it should check if RIGHT (keycode 39) is down and move char 10px to the right if it is; }, 20); </script> 

How to check for a key inside a loop? Btw I also use jQuery on the site.

thanks

+4
source share
3 answers

Use jQuery and keydown :

 <div id="char"></div> <script> $(document).keydown(function(e){ if(e.keyCode == 39){ //do something $("#char").animate({'left':'+=10'}, 1); } }) </script> 

Fiddle: http://jsfiddle.net/maniator/zXeXt/

+2
source

Here I go to raw JS, you would do something like this (click "Preview", then hold w ):

http://jsbin.com/odalo3/edit

 var isPressed = false; var keydown = function(e){ if(e.keyCode == 87){ isPressed = true; } } var keyup = function(e){ isPressed = false; } document.addEventListener("keydown",keydown,false); document.addEventListener("keyup",keyup,false); setInterval(function(){ if(isPressed){ document.getElementById('hello').innerHTML = document.getElementById('hello').innerHTML+', pressed'; } },100) 

UPDATE

If you are using jQuery, you can change eventListeners to:

 $(window).keydown(function(e){ if(e.keyCode == 87){ isPressed = true; } }) .keyup(function(e){ isPressed = false; }) 

And delete these lines:

 var keydown = function(e){ if(e.keyCode == 87){ isPressed = true; } } var keyup = function(e){ isPressed = false; } document.addEventListener("keydown",keydown,false); document.addEventListener("keyup",keyup,false); 

But this is the same.

+4
source

Create a flag var pressed; and set it to true or false in the keyPress event; then check it inside the loop

0
source

All Articles