0
This code is a copy of a video that teaches js to beginners. It is practically an exact copy of what I see on the screen, but with me it does not run at all. The only thing the 'ball' does is go up -10px and back 10px, goes left -10px and back 10px in this sequence. If it reverses (right, low), it doesn’t even move the 10px. This is the only movement. I don’t know what’s wrong. Since the video is 3 years old, it may be outdated in something. I use VS code, win 10.
var caixa = document.querySelector('#caixa');
function mover(evento) {
let tecla = pegaKeyCode(evento);
let posX = 0;
let posY = 0;
if (tecla == 37) {
posX -= 10;
caixa.style.left = posX + "px";
} else if (tecla === 38) {
posY -= 10;
caixa.style.top = posY + 'px';
} else if (tecla === 39) {
posY += 10;
caixa.style.left = posY + "px";
} else if (tecla === 40) {
posX += 10;
caixa.style.top = posX + 'px';
} else if (tecla === 13) {
document.removeEventListener('keydown',
mover(evento));
alert('Suspended movement!')
}
}
function pegaKeyCode(evento) {
let codTecla = evento.keyCode;
return codTecla;
}
document.addEventListener('keydown', mover);
#caixa {
position: absolute;
top: 0px;
left: 0px;
width: 100px;
height: 100px;
border-radius: 50%;
background-color: hsl(210, 100%, 50%);
}
<body>
<div id="caixa" class='caixa'></div>
<script type="text/javascript" src="./js.js">
</script>
</body>
I apologise to everyone for my stupidity. I tried so hard in the code because it didn’t work that I left out something very simple. The variables that are changed are within the function, zeroing out the movement forever. Thank you. P.S I used var to try to rerproduce the original that was coiando. Again thank you and apologies.
– Joao Carlos Agostini