As a coding beginner, I've decided to delve into the world of HTML, CSS, and Javascript by creating a racing game for the browser. However, I seem to have hit a roadblock with error messages popping up whenever I try to control the car:
Cannot read property 'style' of null
Below is my code snippet:
var car = document.getElementById('car');
var container = document.getElementsByClassName('container');
var carLeft = 0;
function anim(e) {
if (e.keyCode==87) {
//W
}
if (e.keyCode==65) {
//A
carLeft+=2;
car.style.left = carLeft + 'px';
}
if (e.keyCode==83) {
//S
}
if (e.keyCode==68) {
//D
carLeft-=2;
car.style.left = carLeft + 'px';
}
}
document.onkeydown =anim;
And here's my CSS styling:
#car {
background-color: blue;
height: 10px;
width: 20px;
z-index: 10;
position: absolute;
left: 0;
}