I just started a CS class at school, so please excuse my total lack of basic knowledge. This JS only works if I put it after the HTML code, not if I put it in the headtag. Shouldn't the window.onload take care of that? Can someone please explain what's wrong? Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#field {
width: 600;
height: 600;
background-color: black;
position: relative;
}
#player {
width: 50;
height: 50;
background-color: red;
position: absolute;
left: 0px;
top: 0px;
}
</style>
<script>
var player = document.getElementById("player");
var playerLeft = 0;
var PlayerTop = 0;
function move(e) {
if (e.keyCode == 68) {
playerLeft += 10
player.style.left = playerLeft + "px";
}
if (e.keyCode == 65) {
playerLeft -= 10
player.style.left = playerLeft + "px";
}
if (e.keyCode == 87) {
PlayerTop -= 10
player.style.top = PlayerTop + "px";
}
if (e.keyCode == 83) {
PlayerTop += 10
player.style.top = PlayerTop + "px";
}
}
function loadEvents() {
document.onkeydown = move;
}
window.onload = loadEvents;
</script>
</head>
<body>
<div id="field">
<div id="player">
</div>
</div>