Im learning html/css/js from a video tutorial. Im learning how to write js code ans i cant help to solve a problem. I hope you give me the solution guys. The problem is about add.EventListener. When i run the code in chrome, in console it shows:"app.js:11 Uncaught TypeError: Cannot read property 'addEventListener' of null" I hope solve this problem with your help. Thank you!
const computerScore = 0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreBoard_div = document.querySelector(".score-board");
const result_div = document.querySelector(".result");
const p_div = document.getElementById("p");
const r_div = document.getElementById("r");
const s_div = document.getElementById("s");
p_div.addEventListener('click', function(){
console.log("hey you clicked p")
})
This is the javescript code - below will be the html code to see any mistakes...
<html>
<head>
<meta charset="utf-8">
<title>Rock Paper Sicssors Game</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="app.js" charset="utf-8"></script>
</head>
<body>
<header>
<h1>Rock Paper Sicssors</h1>
</header>
<div class="score-board">
<div id="user-label" class="badge">user</div>
<div id="computer-label" class="badge">comp</div>
<span id="user-score">0</span>:<span id="computer-score">0</span>
</div>
<div class="result">
<p>Paper covers rock. You win!</p>
</div>
<div class="choices">
<div class="choice" id="p">
<img src="game.image/paper-img.jpg" alt="image" height="42" width="42">
</div>
</div>
<div class="choices">
<div class="choice" id="r">
<img src="game.image/rock-img.jpg" alt="image" height="42" width="42">
</div>
</div>
<div class="choices">
<div class="choice" id="s">
<img src="game.image/siccsors-img.jpg" alt="image" height="42" width="42">
</div>
</div>
<p1 id="action-message">Make your move.</p1>
</body>
</html>
This happens because you're including the file containing your JavaScript in the <head>
section of your html file.
<script type="text/javascript" src="app.js" charset="utf-8"></script>
That means the browser will try to execute this statement
const p_div = document.getElementById("p");
but will fail to do so because the element in question is defined in the <body>
section later on.
Try to move the <script>
section to the end of the <body>
.
Here is how the browser is processing your page:
I would recommend moving your script tag
<script type="text/javascript" src="app.js" charset="utf-8"></script>
to the bottom of your body. Then the browser will ensure all the dom exists before executing your script.
Alternatively, you could do this in your script:
function init() {
// your code
}
And this in your body:
<body onload='init()'>
Which will wait until the body is loaded to execute the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With