Search code examples
javascriptgetelementbyid

I can't reach an element from HTML by using Javascript


I want to create a project with using colors.

All of my files are in the same folder.

I can't reach the my color input that is in the index.html by:

const firstColor = document.getElementById("color1").value;

I can just reach elements which is in the game.js.

Also my canvas is in the game.html.

I have added tags into all of my HTML files.

My index.html:

    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Cyber Bird</title>
  <link rel="stylesheet" href="main.css">
</head>
<body align="center">
  <div id="title">Cyber Bird</div>
  <div id="mainMenu">
    <div id="selectColors">
      <div id="colorsTitle">SELECT <span>2</span> COLORS FOR YOUR <span id="cb">CYBER BIRD</span></div> <br> <hr> <br>
      <span id="first"> First: <input type="color" name="color1" id="color1" value="#f1aabc"></span>
    <span id="second"> Second: <input type="color" name="color2" id="color2" value="#2d96b9"></span>
    </div>
    <a href="game.html" class="button" id="startCyber">START</a>
  </div>
  <script src="src/game.js"></script>
</body>
</html>

My game.html:

      <!DOCTYPE html>
  <html>
  <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <title>Cyber Bird</title>
     <link rel="stylesheet" href="main.css">
  </head>
  <body>
     <div id="container" align="center">
        <div id="scoreBoard">
           <div id="header">SCOREBOARD</div>
           <div id="description">Score: </div>
           <div id="score">0</div>
        </div>

        <canvas id="myCanvas" height="500" width="900"></canvas>
        <div class="helper" id="toJump">press <span>SPACE</span> to jump</div>
        <div class="helper" id="toStart">click <span onclick="startGame()">HERE</span> to start</div>
        <div class="helper" id="toSelect">select new <span><a href="index.html">COLORS</a></span></div>
     </div>
     <div id="darken"></div>
     <div id="gameOver" align="center">
           <div id="message">GAME OVER</div>
           <div id="yourScore">Your score is: <span id="finalScore"></span></div>
           <div id="tryAgain" class="button" onclick="startGame()">Try Again</div>
     </div>
     <script src="game.js"></script>
  </body>
  </html>

Solution

  • You're not passing the data from your index.html to game.html. So when you call this:

    <a href="game.html" class="button" id="startCyber">START</a>

    You're loading a new page, which removes all of your existing variables - including 'color1'.

    I see 2 options here:

    1. Make this a single-page web app. So when you click your START button, it hides the index div and loads a game div
    2. Save your values from index.html somewhere (browser storage?) and then call that after you load your new game.html page.