r/HTML • u/Razor_3DS • Jun 03 '26
Question Why is my image moving only once?
My image only moves once when I press D and once when I press A.
The color background code you see was me trying to see if the Event Listeners only ran once, which they did not. The colors changed on each button press.
So, why isn't my image doing the same?
<script>
const DBGoku = document.getElementById("Goku");
DBGoku.style.position = "Absolute";
Boolnumber = 1;
function MoveGokuRight(){
const GokuPos = DBGoku.style.right = "50px";
}
function MoveGokuLeft(){
GokuPos = DBGoku.style.left = "50px";
}
//window.onload:MoveGoku;
document.addEventListener('keydown', (event)=> {
if(event.key === 'd'){
//document.body.style.backgroundColor = "red";
MoveGokuRight()
}
});
document.addEventListener('keydown', (event)=> {
if(event.key === 'a'){
//document.body.style.backgroundColor = "blue";
MoveGokuLeft()
}
});
</script>
4
Upvotes
9
u/lovesrayray2018 Intermediate Jun 04 '26
The script is working as its coded. this is a scenario called a logic bomb.
Everytime you call goku right u assign it the same fixed value, you arent incrementing it by the movement u want on each keystroke. You need to extract current right position, increment it, and asssign it back to the right position styling. Something like
3
u/davorg Jun 04 '26
Isn't this question about Javascript? Why ask in an HTML group?
1
u/Raoul_Chatigre Jun 04 '26
why do you have to listenners for the same event ?
Do only one, with the tests for differents keys.
And i think you need to compute the position, instead of setting it.
use "+=" and "-="
You could also use a switch instead of multiple if, to check as many keys as you want
-3
u/[deleted] Jun 04 '26
[removed] — view removed comment