I am brand new to exploring JavaScript, HTML, and CSS. I've gone through my code several times but can't quite pinpoint what's causing it not to function properly. While there are no apparent errors being returned, the expected behavior is not occurring. My goal is to have a square displayed on the screen that moves when the WASD keys are pressed. Although the square appears on the screen, nothing happens when pressing WASD. It seems like the solution should be straightforward, yet I'm struggling to find it.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body onkeypress="move(event)">
<style>
#block {
width: 50px;
height: 50px;
background-color: #555;
margin-top: 0px;
margin-left: 0px;
}
</style>
<div id="block"class="block"></div>
<script>
var blockX = 0;
var blockY = 0;
var keyPressed = 0;
function move(event) {
keyPressed = event.keyCode;
if (keyPressed === 87 || keyPressed === 83) {
moveY();
}
else if (keyPressed === 65 || keyPressed === 68) {
moveX();
}
}
function moveX() {
if (keyPressed === 65) {
blockX -= 3;
document.getElementById("block").style.marginLeft = blockX + "px";
}
else if (keyPressed === 68) {
blockX += 3;
document.getElementById("block").style.marginLeft = blockX + "px";
}
}
function moveY() {
if (keyPressed === 87) {
blockY += 3;
document.getElementById("block").style.marginTop = blockY + "px";
}
else if (keyPressed === 83) {
blockY -= 3;
document.getElementById("block").style.marginTop = blockY + "px";
}
}
</script>
</body>
</html>