title: Move an image with the arrow keys using JavaScript
body: <p>I want to be able to move an image around the screen with JavaScript. The code I have below will put the image on the screen but will not let me move it around.</p>
  
  <p>Question: Want to be able to move the image around the screen with the arrow keys?</p>
  
  <p>I am certain there has to be a game loop that somehow is running all the time when the page is active. How this is done I am not certain either but I think that it might be int he  load function.</p>
  
  <p><strong>JavaScript Code:</strong></p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
      &lt;title&gt;Test Move Object&lt;/title&gt;
  
      &lt;script type="text/javascript"&gt;
         &lt;script type="text/javascript"&gt;
  
              function leftArrowPressed() {
              var element = document.getElementById("image1");
              element.style.left = parseInt(element.style.left) - 5 + 'px';
              }
  
              function rightArrowPressed() {
              var element = document.getElementById("image1");
              element.style.left = parseInt(element.style.left) + 5 + 'px';
  
              }
  
              function upArrowPressed() {
              var element = document.getElementById("image1");
              element.style.top = parseInt(element.style.top) - 5 + 'px';
              }
  
              function downArrowPressed() {
              var element = document.getElementById("image1");
              element.style.top = parseInt(element.style.top) + 5 + 'px';
              }
  
              function moveSelection() {
                  evt = evt || window.event; 
                  switch (evt.keyCode) {
                      case 37:
                      leftArrowPressed();
                      break;
                      case 39:
                      rightArrowPressed();
                      break;
                      case 38:
                      upArrowPressed();
                      break;
                      case 40:
                      downArrowPressed();
                      break;
                      }
                  };
  
          function gameLoop()
          {
            // change position based on speed
            moveSelection();
            setTimeout("gameLoop()",10);
          }
  
    &lt;/script&gt;
    &lt;/head&gt;
  
    &lt;body onload="gameLoop()" onkeydown="" onkeyup="" bgcolor='yellow'&gt;
     Test
    &lt;img id="image1" src="C:\Users\itpr13266\Desktop\mp.jpg" style="position:absolute;"
                                                                height="15" width="15"&gt;
    &lt;/body&gt;
     end html
  &lt;/html&gt;
  </code></pre>