1

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 );
codejockie
  • 9,020
  • 4
  • 40
  • 46
Mike
  • 35
  • 6

1 Answers1

2

The counter.js script is being loaded on the document head, i.e. before the #counter element is created. This means that this code:

var clickNumber = document.getElementById("counter");

will result in clickNumber being null (since the element doesn't exist yet).

You can fix this by assigning the clickNumber value once the DOM is loaded:

var counter = 0;
var clickNumber; // still declared outside, but the value is assigned later



function getElementBtnIncrement() {

    document.getElementById("increment").addEventListener("click",increment,false);

}


function increment(){
    counter++;
    clickNumber.innerHTML = "Count = " + counter;
}



window.addEventListener( "load", function() {
  clickNumber = document.getElementById("counter");
  getElementBtnIncrement();
}, false );
Maluen
  • 1,753
  • 11
  • 16