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.
CodePudding user response:
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>
CodePudding user response:
If cube.style.left = "10px"
works as expected for the first click, so it set left property to 10px
. In this case, you need to add 10px
to current Xpx
. Hope this code help you
if(event.key == "d"){
console.log("something")
let cube = document.getElementById("cube")
cube.style.left = `${(parseInt(cube.style.left) 10) || 0}px`
}
CodePudding user response:
The thing is, you don't move the box by 10px to the left everytime you press d but you apply it once. To apply it multiple times you should use a variable that you keep increasing by every button press.
PS: You don't need to use querySelector('body')
as you can simply address it with body
directly:
let left_multiplier = 0;
document.body.addEventListener("keypress", function(event){
console.log(event.key);
if(event.key == "d"){
left_multiplier ;
let cube = document.getElementById("cube")
cube.style.left = `${left_multiplier * 10}px`;
}
})
CodePudding user response:
You can add a variable and store what the current offset position is
Everytime you press "D" you add 10 to the variable.
let leftOffset = 0;
let body = document.querySelector("body")
body.addEventListener("keypress", function(event) {
if(event.key == "d") {
let cube = document.getElementById("cube")
leftOffset = 10;
cube.style.left = `${leftOffset}px`;
}
})
CodePudding user response:
Try this:
let body = document.querySelector("body")
let value = 0
body.addEventListener("keypress", function(event){
if(event.key == "d"){
let cube = document.getElementById("cube")
value = 10
cube.style.marginLeft = value 10 'px'
}
})
When you put cube.style.left = "10px"
you are fixing a value to the style.
But when you do:
value = 10
cube.style.marginLeft = value 10 'px'
You are dynamically updating the style in each key event