Keyboard events
by Génesis García Morilla
CSS
div {
position: absolute;
width: 10px;
height: 10px;
background-color: #3778ff;
}
JavaScript
const step = 10
const $div = document.querySelector('div')
document.onkeydown = event => {
switch (event.code) {
case 'ArrowUp':
$div.style.top = `${parseInt($div.style.top || 0) - step}px`
break
case 'ArrowRight':
$div.style.left = `${parseInt($div.style.left || 0) + step}px`
break
case 'ArrowDown':
$div.style.top = `${parseInt($div.style.top || 0) + step}px`
break
case 'ArrowLeft':
$div.style.left = `${parseInt($div.style.left || 0) - step}px`
break
case 'KeyR':
if (event.altKey) $div.style.top = $div.style.left = 0
break
}
}