I am wondering how I can make my code repeat, actually how the square can move next 10px. When I press "d" key, the square mooves, but when i click on it again, nothing happens. It’s because I set the position to 10px, but I cant figure out new naw how to do it.
My code:
let body = document.querySelector("body")
body.addEventListener("keypress", function(event){
console.log(event.key)
if(event.key == "d"){
console.log("something")
let cube = document.getElementById("cube")
cube.style.left = "10px"
}
})
Any tips? Thank you.
>Solution :
let body = document.querySelector("body")
body.addEventListener("keypress", function(event){
console.log(event.key)
if(event.key == "d"){
console.log("something")
let cube = document.getElementById("cube");
const left = cube.style.left || 0;
cube.style.left = `${parseInt(left) + 10}px`;
}
})
#cube {
width: 10px;
height: 10px;
position: absolute;
top: 10px;
left: 0;
background:red;
}
<div id="cube">
</div>