Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to repeat code in if statement inside event listener

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading