Nadia Nadia - 7 months ago 12
Javascript Question

Count on click button1 and recount if on click button2

I have two buttons and a counter, I have to reset counter every time I change the button. I don't know how to reset the counter.



var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");

function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
clickCount();
count=0;
}
button2.onclick = function(){
clickCount();
}

<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>




Answer

Pass a parameter to your clickCount function with the button name, and check if it has changed.

var count = 0;
var lastButtonClicked = "";
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");

function clickCount(buttonName){
  if (buttonName === lastButtonClicked)
  {
     count++;
  }
  else
  {
     count = 1;
     lastButtonClicked = buttonName;
  }
  display.innerHTML = count;
}		
button1.onclick = function(){
  clickCount("1");
}
button2.onclick = function(){
  clickCount("2");
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>