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
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
Share Improve this question edited May 23, 2011 at 21:34 lisovaccaro asked May 23, 2011 at 21:21 lisovaccarolisovaccaro 34.1k99 gold badges271 silver badges423 bronze badges 3- 1 are you using any libraries like jQuery or just raw JS? – Oscar Godson Commented May 23, 2011 at 21:22
- Similar: stackoverflow./questions/2445613/… – spanky Commented May 23, 2011 at 21:38
- See my updated answer... added jQuery too if you want – Oscar Godson Commented May 23, 2011 at 21:38
3 Answers
Reset to default 4Here ya go in raw JS you'd do something like this (press Preview then hold down w
):
http://jsbin./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.
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/maniator/zXeXt/
Create a flag var pressed;
and set it to true or false in keyPress event; then check it inside the loop