PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to prevent a click event on a button from triggering by using another button in javascript?

 October 15, 2022     dom, event-handling, html, javascript     No comments   

Issue

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;
});

Solution

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>



Answered By - CertainPerformance
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing