how to make the button only once click

Issue

Guys I put (like and dislike button not with facebook) my site.And I want to show like values and dislike values.I did but I want just once click.How can I do ?

  var clicks = 0;
function updateClickCount() {
    document.getElementById("clickCount").innerHTML = clicks;
}





 onClick="clicks--; updateClickCount();
 onClick="clicks++; updateClickCount();

I expect the button of once click , but the actual button as much as you want.

Solution

You can remove the event listener, after the button gets clicked using removeEventListener. Do keep in mind that the parameters supplied in the removeEventListener call must be identical with the ones supplied to the addEventListener call, otherwise it won’t work.

var button = document.getElementById("btn");
button.addEventListener("click", onClick);

function onClick() {
  console.log("Clicked");
  button.removeEventListener("click", onClick);
}
<button id="btn">Click Me!</button>

If you have added the listener inline (using onClick="" attribute), you can’t use removeEventListener. You can however remove the onClick attribute.

var button = document.getElementById("btn");

function onClick() {
  console.log("Clicked");
  button.removeAttribute("onClick");
}
<button id="btn" onClick="onClick()">Click Me!</button>

You could disable the button, making it un-clickable.

var button = document.getElementById("btn");
button.addEventListener("click", onClick);

function onClick() {
  console.log("Clicked");
  button.disabled = true;
}
<button id="btn">Click Me!</button>

You can use a Promise (Promises can only be resolved once).

var button = document.getElementById("btn");
new Promise(function(resolve) {
  button.addEventListener("click", resolve);
}).then(onClick);

function onClick() {
  console.log("Clicked");
}
<button id="btn">Click Me!</button>

Finally you store the info of whether the button has been clicked or not in a boolean variable.

var button = document.getElementById("btn");
var buttonFlag = false;
button.addEventListener("click", onClick);

function onClick() {
  if (buttonFlag) return;
  console.log("Clicked");
  buttonFlag = true;
}
<button id="btn">Click Me!</button>

Update

You can now also use the once property so that the event only runs once (or never if it’s never triggered).

var button = document.getElementById("btn");
button.addEventListener("click", () => console.log("Clicked"), {
  once: true
});
<button id="btn">Click Me</button>

Answered By – nick zoum

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.