javascriptanimation

How do I animate an image to move on command?


I have a code here which is to make this image move to the left if the left arrow key is pressed, however it does not seem to be doing much of anything

   let posx = 0;
document.getElementById("ship").addEventListener("ArrowLeft", moveLeft);
function moveLeft(){
    if (event.code == "ArrowLeft"){
        posx -= 2
    }
}

Solution

  • I dont believe that "ArrowLeft" is an event for which the ship element can listen. Consider using the "keydown" event instead

    var posX = 100;
    
    document.addEventListener("keydown", function(event) {
      var notPressedElement = document.getElementById("notPressed");
      var pressedElement = document.getElementById("Pressed");
      var keyElement = document.getElementById("keyName");
      notPressedElement.style.visibility = "hidden";
      pressedElement.style.visibility = "visible";
      keyElement.innerText = event.key;
    
      switch (event.key) {
        case "ArrowLeft":
          posX -= 2;
          break;
        case "ArrowRight":
          posX += 2;
          break;
        default:
          break;
      }
    
      var posXElement = document.getElementById("posXValue");
      posXElement.innerText = posX.toString();
    });
    
    document.addEventListener("keyup", function(event) {
      var notPressedElement = document.getElementById("notPressed");
      var pressedElement = document.getElementById("Pressed");
      var keyElement = document.getElementById("keyName");
      notPressedElement.style.visibility = "visible";
      pressedElement.style.visibility = "hidden";
      keyElement.innerText = "";
    });
    <div id="demoDiv">
      <div id="notPressed" style="visibility: visible;">
        <h3>Key Pressed: None</h3>
      </div>
      <div id="Pressed" style="visibility: hidden;">
        <h3>Key Pressed: <span id="keyName"></span></h3>
      </div>
    </div>
    <div>
      <h3>PosX = <span id="posXValue">100</span></h3>
    <div>