I want to run specific piece of code repeatedly as long as arrow keys are pressed. I have tried to pick up as much things as I can in a week about JavaScript and have written this code (see below), but it isn't working. Right now I am trying to print a something on the page, but in final implementation I would need to run a file repeatedly. Also I would like to know a way to print the results of newly executed function without erasing anything that's already on the screen.
<html>
<head>
<title>
</title>
</head>
<body>
<script>
document.write("Script loaded <br/>");
document.onkeydown=initiate;
function initiate{
$(document).keydown(function(event) {
keyCode=event.keyCode;
event.preventDefault();
});
}
if(keyCode==38){
window.setInterval({a()},100);
function a(){
document.write("Up key</br>");
}
else if(keyCode==39){
window.setInterval({b()},100);
function b(){
document.write("Right key</br>");
}
else if(keyCode==40){
window.setInterval({c()},100);
function c(){
document.write("Down key</br>");
}
else if(keyCode==41){
window.setInterval({d()},100);
function d(){
document.write("Left key</br>");
}
</script>
</body>
</html>
P.S.: Please excuse my bad scripting skills. I tried to grasp everything in a hurry in order to integrate it into a project I am working on.
Problems in your code
if-else
block is not correct.$(document).keydown
is jQuery, not native JavaScript, you don't need it.Code: