Home > Software engineering >  Why does my JavaScript variable return 'null' instead of Html?
Why does my JavaScript variable return 'null' instead of Html?

Time:03-20

I have some JavaScript that is not working:


    const player = document.getElementById("player");
    console.log(player);
    
    var positionX = 600;
    var positionY = 200;
    
    document.onkeypress = function move(e) {
      console.log(e.key);
      let keyPressed = e.key;
      if (keyPressed == 'w') {
        positionY--;
        player.style.top = positionY   'px';
        console.log(player);
      }
    };

And in the console, the 'player' variable prints as 'null' when I have tried setting it to the 'player' div in my Html.

Here is the Html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Movement</title>
    <link rel="stylesheet" href="index.css">
    <script src="index.js" charset="utf-8"></script>
  </head>
  <body>

    <div id="player"></div>

  </body>
</html>

An error also shows up:

index.js:12 Uncaught TypeError: Cannot read properties of null (reading 'style')
    at HTMLDocument.move (index.js:12:12)
move @ index.js:12

Can someone help me?

CodePudding user response:

This is because your JavaScript searches for the element before the DOM is rendered, so the player variable is instead null.

You can add the script after the player div:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Movement</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>

    <div id="player"></div>
    <script src="index.js" charset="utf-8"></script>
  </body>
</html>

or wait for the DOM to be rendered with

document.addEventListener("DOMContentLoaded", () => {
  const player = document.getElementById("player");
    console.log(player);
    
    var positionX = 600;
    var positionY = 200;
    
    document.onkeypress = function move(e) {
      console.log(e.key);
      let keyPressed = e.key;
      if (keyPressed == 'w') {
        positionY--;
        player.style.top = positionY   'px';
        console.log(player);
      }
    };
});

CodePudding user response:

You should put you script inside window.onload()

Example :

window.onload = () => {
    /* put you script here */
}

Or call you js file at bottom of HTML

Because you script executed before all html element ready !

  • Related