Search code examples
javascriptcssevent-listenerpongarrow-keys

How can I get a div that moves using arrow keys to not be able to go off screen?


I want to make a pong game using HTML, CSS and javascript. I started with making a player and I got it to move using the arrow keys but it can go outside the screen which creates the sidebar. I want it to not be able to go off the screen. Here is the javascript code:

const right = document.getElementById("right");

const player = document.createElement("player");
player.classList.add("player");
right.appendChild(player);

player.style.top = "300px";
player.style.left = 5;

let moveBy = 10;
window.addEventListener("keydown", (event) => {
  switch (event.key) {
    case "ArrowUp":
      player.style.top =
        parseInt(player.style.top) - moveBy + "px";
      break;
    case "ArrowDown":
      player.style.top =
        parseInt(player.style.top) + moveBy + "px";
      break;
  }
});

I tried adding if statements but it did not work, I have also tried to google it but I have not found the right answer for this.


Solution

  • You need position: absolute; to make top setting work.

    player.style.position = "absolute";
    

    Then set the range of top (0 ~ window.innerHeight)

    let top,
      max = window.innerHeight - 30;
    switch (event.key) {
      case "ArrowUp":
        top = parseInt(player.style.top) - moveBy;
        break;
      case "ArrowDown":
        top = parseInt(player.style.top) + moveBy;
        break;
    }
    player.style.top = top > max ? max : top < 0 ? 0 : top + "px";