I plan to make this box move every time I click a button
but the problem is that it works first time when I click s
or d
but does not work after that.
So can any one help me to find the solution to my problem?
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
left: 10px;
top: 20px;
width: 20px;
height: 20px;
background-color: black;
border: 1px solid black;
border-radius: 5px;
}
</style>
</head>
<body id="bd">
<div class="box"></div>
<script >
document.getElementById('bd').addEventListener('keypress', show);
function show(e){
let x = e.which;
if(x == 122){
// 122 = z
document.getElementsByClassName('box')[0].style.top -='50px' ;
}
else if(x == 133){
// 122 = q
document.getElementsByClassName('box')[0].style.left -='50px' ;
}
else if(x == 115){
// 122 = s
document.getElementsByClassName('box')[0].style.top +='50px' ;
}
else if(x == 100){
// // 122 = d
document.getElementsByClassName('box')[0].style.left +='50px' ;
}
}
</script>
</body>
</html>
You are trying to perform operation on string. First need to convert in number.
Sample:
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
left: 10px;
top: 20px;
width: 20px;
height: 20px;
background-color: black;
border: 1px solid black;
border-radius: 5px;
}
</style>
</head>
<body id="bd">
<div class="box"></div>
<script>
const number = (num) => Number(num.split('px')[0])
const addBy50 = (num) => `${number(num) + 50}px`
const subtractBy50 = (num) => `${number(num) - 50}px`
const style = document.getElementsByClassName("box")[0].style
document.addEventListener("keypress", (e) => {
let x = e.which;
const {
top,
left
} = style
switch (e.which) {
case 122:
style.top = subtractBy50(top);
break;
case 113:
style.left = subtractBy50(left);
break
case 115:
style.top = addBy50(top);
break
case 100:
style.left = addBy50(left);
break
}
});
</script>
</body>
</html>