I have error there: Uncaught TypeError: Cannot read property ‘addEventListener’ of null
Some one have any idea?
HTML
<button id="p1">Player One</button>
JS
`var p1Button = document.querySelector("#p1");
var p2Button = document.getElementById(“p2”);
var h1 = document.querySelector(“h1”);
var p1Score = 0;
p1Button.addEventListener(“click”, function(){
p1Score++;
console.log(p1Score);
h1.textContent = p1Score;
});
`
MK-61
2
Is it really unchanged source?
Then remove “HTML” and JS with ` after it, so your source will be like:
<button id="p1">Player One</button>
var p1Button = document.querySelector("#p1");
var p2Button = document.getElementById("p2");
var h1 = document.querySelector("h1");
var p1Score = 0;
p1Button.addEventListener("click", function(){
p1Score++;
console.log(p1Score);
h1.textContent = p1Score;
});
The problem is that before first “var” was “`” - that was causing error like p1Button wasn’t initialized.
HTML and JS with ’ after it added by me
i don’t understand why p1Button = null
MK-61
4
Can you show full source somehow? Codepen link?
1 Like
The problem solved. Just moved string <script type="text/javascript" src="score.js"></script>
to end of HTML before <body>
.
MK-61 thx for help!
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1>0 to 0</h1>
<p>Playing to: 5</p>
<input type="number">
<button id="p1">Player One</button>
<button id="p2">Player Two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score.js"></script>
</body>
</html>
1 Like