0

I have a button with id "myButton" when clicked it should increase the count in span with id "clickCount" by 1 every time, the other button has an id "deactivate", when clicked it should no longer allow the increase in count even if the button with id "myButton" is clicked, I can manage upto the increase in count, but don't know how to stop the count from increasing without disabling the first button.

HTML

<button id="myButton">Click me!</button>
<p>You clicked on the button <span id="clickCount">0</span> times</p>
<button id="deactivate">Désactivate counting</button>

Javascript

let myButton = document.getElementById('myButton');
let newCount = document.getElementById('clickCount');
let deact = document.getElementById('deactivate');
let count = 0;
 myButton.addEventListener("click", function() {
 count++;
 newCount.innerText = count;
});
3
  • you can add an event listener in the button that controls if the counter button is disabled or not. Commented May 19, 2020 at 21:12
  • Did you consider to deactivate myButton on click of deactivate? Commented May 19, 2020 at 21:12
  • I have to do it without disabling the "myButton" button. Commented May 19, 2020 at 21:46

2 Answers 2

1

Remove the event listener from #myButton when the other button is clicked

let myButton = document.getElementById('myButton');
let newCount = document.getElementById('clickCount');
let deact = document.getElementById('deactivate');
let count = 0;
function handler() {
  count++;
  newCount.innerText = count;
}

myButton.addEventListener('click', handler);
deact.addEventListener('click', () => myButton.removeEventListener('click', handler));
<button id="myButton">Click me!</button>
<p>You clicked on the button <span id="clickCount">0</span> times</p>
<button id="deactivate">Désactivate counting</button>

Sign up to request clarification or add additional context in comments.

Comments

1

You can add a boolean that changes to true on deactivation and allows increment when it is false:

let myButton = document.getElementById('myButton');
let newCount = document.getElementById('clickCount');
let deact = document.getElementById('deactivate');
let count = 0;
let deactivated = false;
deact.addEventListener("click", function(){
     deactivated = true;
});
myButton.addEventListener("click", function() {
     if(!deactivated){
          count++;
          newCount.innerText = count;
     }
});
<button id="myButton">Click me!</button>
<p>You clicked on the button <span id="clickCount">0</span> times</p>
<button id="deactivate">Désactivate counting</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.