0

I am trying to use keyboard events, but I just can do it using the first event, in this case, key-down, but when I try key-up nothing happens.

const box = document.createElement("div")
box.setAttribute("id", "box")
document.querySelector("body").appendChild(box)

let boxTop = 20;
let boxLeft = 20;

document.addEventListener("keydown", (e) => {
    let keyName = e.key
    if(keyName === "ArrowDown") {
        box.style.top = boxTop + "10px"
    }
})

document.addEventListener("keyup", (e) => {
    let keyName = e.key
    if(keyName === "ArrowUp") {
        box.style.top = boxTop - "10px"
    }
})
mplungjan
  • 169,008
  • 28
  • 173
  • 236

2 Answers2

3

You need position absolute and you need to use

(boxTop + 10)+"px"
(boxTop - 10)+"px"

Change plus and minus to

+= and -= if you want to continue to move

Perhaps test you are at top?

Why not use keyDown on both event handlers?

const box = document.createElement("div")
box.setAttribute("id", "box")
document.querySelector("body").appendChild(box)

let boxTop = 20;
let boxLeft = 20;

document.addEventListener("keydown", (e) => {
  let keyName = e.key
  if (keyName === "ArrowDown") {
    box.style.top = (boxTop += 10)+"px"
  }
})

document.addEventListener("keyup", (e) => {
  let keyName = e.key
  if (keyName === "ArrowUp") {
    let  top = (boxTop -= 10);
    if (top<0) top = 0; // unleess you want them to move out of viewport
    box.style.top = top+"px"
  }
})
div { border: 1px solid black; height: 100px; width:100px;  position: absolute;  }
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

The event happened. There is no change because of this.

box.style.top = boxTop - "10px"
box.style.top = boxTop + "10px"

Please change it.

box.style.top = boxTop - 10 + "px"
box.style.top = boxTop + 10 + "px"
Kirill Savik
  • 1,228
  • 4
  • 7