-1

Im trying to recreate the brick breaker game from scratch but I cant seem to get this element to move. I open google chrome development tools and it tells me

Uncaught TypeError: Cannot read properties of null (reading 'style') I have tried everything I could think of but nothing seems to work, help would be great, thanks.

let userObject = document.querySelector('#user') ; 


window.addEventListener('load', () =>{
document.getElementById('user').style.position = 'absolute' ; 
userObject.style.position = "absolute";  });
window.addEventListener('keyup', (event) => {
switch (event.key) {
    case 'ArrowLeft':
        userObject.style.left = parseInt(userObject.style.left) - 5 + 'px';
        break;
    case 'ArrowRight':
        userObject.style.left = parseInt(userObject.style.left) + 5 + 'px';
        break;
    case 'ArrowUp':
        userObject.style.top = parseInt(userObject.style.top) - 5 + 'px';
        break;
    case 'ArrowDown':
        userObject.style.top = parseInt(userObject.style.top) + 5 + 'px';
        break;
    default:
        alert("Only Arrow Keys Are Allowed!");
} });
#userbox { 
  display : flex ;
  align-items: center;
  justify-content: center;
  height: 100vh;
  width : 100% ;
}



#user { 
  display : flex ; 
  width: 70px ;
  height : 10px ; 
  background-color : black ;
}
<div id = "userbox"><span id= "user"> </span></div>

Any help would be great. Thank you all.

Samball
  • 623
  • 7
  • 22
  • Move `let userObject = ...` into the `load` event handler (and why do you use `document.getElementById('user').style.position = ...` in there instead of `userObject`?) – Andreas Apr 12 '22 at 07:17

1 Answers1

0

I think script runs before html rendering so it first finds user element so userObject will be null.

Solution is ->Declare userObject in window onload event listener or -> use async/defer keyword where you import the script

vinesh_dodiya
  • 140
  • 1
  • 13