The code looks fine but still gets the error added event handler also
document.addEventListener('DOMContentLoaded', function() {
let count = 0
let countEl = document.getElementById("count-el")
function increment() {
count = count + 1
countEl.innerText=count;
// set countEl's innerText to the count
}
increment()
countEl.addEventListener("click", increment);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./index.js"></script>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<h1>People entered:</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
</body>
</html>
Please check the code, the error shows for this line INCREMENT Specifically for "INCREMENT" in that line
2
Answers
The function
increment
is defined inside the event listener. So it is inaccessible out side the event listener. So you need to define your function outside of the event listener to access it. You can keep thecountEl.addEventListener("click", increment)
inside yourDOMContentLoaded
event and it would work fine.A good practice is to avoid polluting global namespaces with variables and constants. In fact, you wasn’t very far at all.
In your code, it seems there’s a bit of confusion between the rendering of the counter (in
h2#count-el
I presume) and the trigger (the INCREMENT button).It also ensures you won’t face errors if one is clicking your button before the script have been loaded (it will simply do nothing).