Search code examples
javascripthtmlkeyboard-events

Shouldn't this HTML run correctly?


I used editor.cloxy.net to program this (more about that site on my profile) but I cleaned it up to make it easier to read. I've been interested in HTML/CSS/JavaScript for about a year, but it is still pretty hard to make a simple program. I recently learned about key codes and made the script down below, but it didn't work so I made an account and asked the question. The code doesn't return an error, but it doesn't do what I intended: moving left when the player presses the left key, moving right when the player presses the right key, and etc. Here is the code:

<!DOCTYPE html>
<html>
<head>
    <title>A test</title>
    <style>
         #a {
           position: absolute;
         }
    </style>
</head>
<body>
    <button id="a">thing</button> 
    <script>
     var x = a.style.left
     var y = a.style.top
     document.onkeydown = function(e) {
         switch (e.keyCode) {
             case 37: //left
                 x -= 10
                 a.style.left = x + "px";
                 break;
             case 38: //up
                 y -= 10
                 a.style.top = y + "px";
                 break;
             case 39: //right
                 x += 10
                 a.style.left = x + "px";
                 break;
             case 40: //down
                 y += 10
                 a.style.top = y + "px";
                 break;
         }
       };
    </script>
</body>
</html>

I am hoping for a helpful answer, like I see on other questions. Please try and help :)


Solution

  • You need to properly parse/initialize your x and y values:

    var x = parseInt(a.style.left) || 0;
    var y = parseInt(a.style.top) || 0;
    
    document.onkeydown = function(e) {
      switch (e.keyCode) {
        case 37: //left
          x -= 10
          a.style.left = x + "px";
          break;
        case 38: //up
          y -= 10
          a.style.top = y + "px";
          break;
        case 39: //right
          x += 10
          a.style.left = x + "px";
          break;
        case 40: //down
          y += 10
          a.style.top = y + "px";
          break;
      }
    };
    #a {
      position: absolute;
    }
    <button id="a">thing</button>