I'm trying to move the button through the body using arrows. It's wrong to put numeric literals, and I tested that the code it's linked to the HTML.
document.body.addEventListener("keydown", function (evt) {
const btn = document.querySelector('button');
switch(evt.code) {
case 'ArrowUp':
btn.style.marginBottom =+ 10;
break;
case 'ArrowDown':
btn.style.marginTop =+ 10;
break;
case 'ArrowRight':
btn.style.marginLeft += 10;
break;
case 'ArrowLeft':
btn.style.marginRight =+ 10;
break;
default:
}
})
marginLeft and other return a string (with "px" text), so you have to remove it in order to make sum.
document.body.addEventListener("keydown", function (evt) {
const btn = document.querySelector('#mybutton');
switch(evt.code) {
case 'ArrowUp':
btn.style.marginTop = (parseInt(btn.style.marginTop.replace("px","")) - 10) + "px";
break;
case 'ArrowDown':
btn.style.marginTop = (parseInt(btn.style.marginTop.replace("px","")) + 10) + "px";
break;
case 'ArrowRight':
btn.style.marginLeft = (parseInt(btn.style.marginLeft.replace("px","")) + 10) + "px";
break;
case 'ArrowLeft':
btn.style.marginLeft = (parseInt(btn.style.marginLeft.replace("px","")) - 10) + "px";
break;
default:
}
})
<div>before</div>
<button id="mybutton" style="margin:1px">hello</button>
<div>after</div>