redliz5808
redliz5808

Reputation: 107

Up and Down Arrows Aren't Working with onkeydown in JavaScript

I'm building a simple obstacle game and the problem I'm having right now is that I can use the arrow keys to move left and right, but not up and down. I don't get why up and down don't work when they have the same logic as left and right. I'm fairly new to developing things on my own so go easy on me if it's obvious. :)

document.addEventListener("DOMContentLoaded", () => {
  // Grab the elements from the HTML
  const floppy = document.getElementById("floppyDisk");
  const gameBoard = document.querySelector(".gameBoard");

  let userScore = document.getElementById("userScore");
  let highscore = document.getElementById("highscore");

  // Set up variables to be used later
  let floppyPosX = 0;
  let floppyPosY = 0;
  let left = 20;
  let top = 190;

  // Use the arrows to move the floppy disk
  function moveFloppy(e) {
    if(e.keyCode == 39) {
      left += 2;
      floppy.style.left = floppyPosX + left + "px";
    }
    if(e.keyCode == 37) {
      left -= 2;
      floppy.style.left = floppyPosX + left + "px";
    }
    if(e.keycode == 38) {
      top += 2;
      floppy.style.top = floppyPosY + top + "px";
    }
    if(e.keycode == 40) {
      top -= 2;
      floppy.style.top = floppyPosY + top + "px";
    }
  }

  // Invoke the moveFloppy function
  document.onkeydown = moveFloppy;
  
  // Generate Obstacles
  
    // Function to move the obstacles

    // Set function to repeat


  // Call the function to generate the obstacles

})

Upvotes: 2

Views: 2330

Answers (1)

Dai
Dai

Reputation: 155250

Your problem is because you're using the deprecated (and ill-defined) KeyboardEvent.keyCode property instead of the standardised code property.

Change your JavaScript to this and it should work:

function moveFloppy(e) {
    switch(e.code) {
    case 'ArrowLeft':
        left += 2;
        floppy.style.left = floppyPosX + left + "px";
        break;
    case 'ArrowRight':
        left -= 2;
        floppy.style.left = floppyPosX + left + "px";
        break;
    case 'ArrowUp':
        top += 2;
        floppy.style.top = floppyPosY + top+ "px";
        break;
    case 'ArrowDown':
        top -= 2;
        floppy.style.top = floppyPosY + top + "px";
        break;
    default:
        // TODO: Play a fart sound.
        break;
    }
}

document.addEventListener( 'keydown', moveFloppy );

Upvotes: 2

Related Questions