4

I want to add a condition inside a loop that tests if the right arrow is pressed and if it is move a div a bit to the right. However I don't know how to check for they keydown.

I'm using a code to do it but it is really long and I'm sure there is an shorter way to do it.

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 can I check for keydown inside the loop? Btw I'm also using jQuery on the site.

Thanks

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

3 Answers3

4

Here ya go in raw JS you'd do something like this (press Preview then hold down 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 the 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 it's the same thing.

Oscar Godson
  • 31,662
  • 41
  • 121
  • 201
2

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/

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • @Oscar, actually i think i made a mistake, it should be bound to `$(document)` (updated the fiddle) – Naftali May 23 '11 at 22:09
0

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

Andrey
  • 20,487
  • 26
  • 108
  • 176
  • 2
    This sounds right to me. I don't know why it was downvoted. I gave you an upvote. – Zach May 23 '11 at 21:31
  • 1
    You should set it to `true` on `keydown` and to `false` on `keyup`. – lonesomeday May 23 '11 at 21:35
  • The problem is that the "keypress" event by itself won't let you know when the "keyup" happens. – Pointy May 23 '11 at 21:43
  • This whole answer is pretty vague IMO. – Oscar Godson May 23 '11 at 21:45
  • @Oscar - it's only vague if you don't know anything about JavaScript. Yes, it wasn't a full answer as I didn't have time at work, but I gave a very clear idea for the OP to start with, and it shouldn't have been down voted. – Andrey May 24 '11 at 00:55