<html>
<head>
<title>Keyboard Events Demo</title>
</head>
<body>
<h1>Keyboard Events Demo</h1>
<p>Use arrow keys to move the player (the red box).</p>
<div id="player"></div>
</body>
</html>
xxxxxxxxxx
#player {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
xxxxxxxxxx
var player = document.getElementById('player');
var playerTop = 50;
var playerLeft = 50;
document.addEventListener('keydown', function(event) {
var key = event.key;
if (key === 'ArrowUp') {
playerTop -= 10;
} else if (key === 'ArrowDown') {
playerTop += 10;
} else if (key === 'ArrowLeft') {
playerLeft -= 10;
} else if (key === 'ArrowRight') {
playerLeft += 10;
}
player.style.top = playerTop + '%';
player.style.left = playerLeft + '%';
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.