0

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.

Eren
  • 13
  • 1
  • 4

2 Answers2

4

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>
nick zoum
  • 7,216
  • 7
  • 36
  • 80
0

If you want to create custom like/dislike function, try to check button click with cookies. If you disable button after the button gets clicked, user will be able to click the button when the page is reloaded. Check cookie, if it exists - don't process click event, if not - increase/decrease like value and set cookie. here you can read about using cookies with javascript Onclick javascript cookie, Set cookie and get cookie with JavaScript

Avilona
  • 121
  • 3