I need to make a counter that attaches a click event handler to the increment button. There must be 2 functions and the variables must be declared outside the functions. Why is it not able to read the value of clickNumber
? If I declare the value inside the increment function it works.
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Counter</title>
<script src="counter.js"></script>
</head>
<body>
<div>
<button id="increment">Increment</button>
<p id="counter">Counter = 0</p>
</div>
</body>
</html>
JS
var counter = 0;
var clickNumber = document.getElementById("counter");
function getElementBtnIncrement() {
document.getElementById("increment").addEventListener("click",increment,false);
}
function increment(){
counter++;
clickNumber.innerHTML = "Count = " + counter;
}
window.addEventListener( "load", getElementBtnIncrement, false );