Amadi
Amadi

Reputation: 23

Incrementing a displayed number upon a button click

I would like to increment the number displayed by the h3 tag whenever the button is pressed but can't seem to find the solution to do this.

var outPut = document.querySelector("#outPut");
var button1 = document.querySelector("#button1");

button1.addEventListener("click", () => {
  var num = 0;
  num += 1;
  outPut.innerHTML = num; 
})
<h1>Counter</h1>
<div id="display">
  <h3 id="outPut">0</h3>
</div>
<button id="button1">Count Up</button>
<button id="button2">Count Down</button>
<button id="button3">Count Up X2</button>
<button id="button4">Count Down X2</button>

Upvotes: 0

Views: 416

Answers (1)

Mamun
Mamun

Reputation: 68933

You have declared the variable (num) in the wrong scope. Since you have declared the counter variable (num) inside the function, in each click the variable is created with the initial value 0. To retain the previous value declare the variable outside the function.

Also, I will suggest you to use innerText or textContent instead of innerHTML if the text is a plain text (not htmlString).

var outPut = document.querySelector("#outPut");
var button1 = document.querySelector("#button1");
var num = 0;
button1.addEventListener("click", () => {
  num += 1;
  outPut.textContent = num; 
})
<h1>Counter</h1>
<div id="display">
  <h3 id="outPut">0</h3>
</div>
<button id="button1">Count Up</button>
<button id="button2">Count Down</button>
<button id="button3">Count Up X2</button>
<button id="button4">Count Down X2</button>

Upvotes: 1

Related Questions