Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my JavaScript variable return 'null' instead of Html?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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?

>Solution :

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);
      }
    };
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading