Home > OS >  How can I prevent a user from clicking a button multiple times?
How can I prevent a user from clicking a button multiple times?

Time:02-04

I am currently creating a game where the goal is to guess flags that are displayed, with a scoring system. It works well overall, but I would like it if, when the answer is validated and correct (and the score is incremented), it is not possible to press it again, otherwise it allows the score to be incremented ad infinitum.

Similarly, I have a button that gives the answer if the user does not find it. I would like it to be impossible for the user to give an answer and validate it in this case.

I tried to use the function javascript element.disabled = true but it blocks the answer for the questions according to this is not the purpose. To limit I also tried to make a click counter that locks at 1 but it has no effect I think. I would like to know if someone could explain me the steps to follow and instructions.

function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

let flag = "Cambodia";
ans = false;
answerDisplayed = false
score = 0;

function getVal() {
  const inputValue = document.querySelector('input').value;

  if (inputValue.toLowerCase() != flag.toLowerCase()) {
    document.querySelector('.result').classList.add("result-false");
    document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
    document.querySelector('.result').style.color = "red";
    ans = false;

  } else {
    document.querySelector('.result').classList.add("result-true");
    document.querySelector('.result').innerHTML = 'Bonne Réponse';
    document.querySelector('.result').style.color = "green";
    ans = true;
    score = score   1;
    document.querySelector('.score').innerHTML = score;
  }
}

function getData() {
  var json = 'https://cdn.jsdelivr.net/npm/[email protected]/dist/index.json'
  fetch(json)
    .then(data => data.json())
    .then(data => {
      const randomInt = getRandomInt(data.length);
      console.log(data[randomInt]);
      var image = document.getElementById("flag");
      image.src = data[randomInt].image;
      flag = data[randomInt].name;
    });
  document.querySelector('.result').innerHTML = '';
  document.querySelector('.result').innerHTML = '';
}

function getAnswer() {
  document.querySelector('.result').innerHTML = flag;
  document.querySelector('.result').style.color = "white";
  document.querySelector('.next').disabled = true;
  document.querySelector('.skip').innerHTML = 'Drapeau suivant';
}

function skip() {
  getData();
  document.querySelector('.next').disabled = false;
  document.querySelector('.skip').innerHTML = 'Je passe';
}

function next() {
  if (ans == true) {
    getData();
    inputValue = "";
  } else {
    document.querySelector('.result').innerHTML = 'Entrez la bonne réponse';
  }
}
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600&display=swap" rel="stylesheet">
<script>
  window.onload = function() {
    getData();
    document.querySelector('.score').innerHTML = score;
  };
</script>

<h1>GuessTheFlag</h1>

<div >
  <div >
    <h3>Score : <span ></span></h3>
    <img width="100" id="flag" src="" alt="">
  </div>

  <div >
    <input type="text" name="flagName" placeholder="Nom du pays">
    <button type="submit" onclick="getVal()" >Je valide</button>
  </div>

  <p ></p>
  <p ></p><br>

  <div >
    <button onclick="next()" >Suivant</button>
    <button onclick="getAnswer()" >Réponse</button>
    <button onclick="skip()" >Je passe !</button>
  </div>

  <p>*Les réponses doivent être données en Anglais. <br>Pensez à valider votre réponse avant de passer à la suivante</p>
</div>

CodePudding user response:

The issue you're running into is due to the use of onclick inside of the button. A better approach is to use addEventListener and removeEventListener to add/remove event callbacks.

function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

let flag = "Cambodia";
ans = false;
answerDisplayed = false
score = 0;

const validateButton = document.getElementById("validate");
validateButton.addEventListener("click", getVal);

function getVal() {
  const inputValue = document.querySelector('input').value;

  if (inputValue.toLowerCase() != flag.toLowerCase()) {
    document.querySelector('.result').classList.add("result-false");
    document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
    document.querySelector('.result').style.color = "red";
    ans = false;
    alert(false);
  } else {
    document.querySelector('.result').classList.add("result-true");
    document.querySelector('.result').innerHTML = 'Bonne Réponse';
    document.querySelector('.result').style.color = "green";
    ans = true;
    score = score   1;
    document.querySelector('.score').innerHTML = score;
  }
  validateButton.removeEventListener("click", getVal);
}

function getData() {
  var json = 'https://cdn.jsdelivr.net/npm/[email protected]/dist/index.json'
  fetch(json)
    .then(data => data.json())
    .then(data => {
      const randomInt = getRandomInt(data.length);
      console.log(data[randomInt]);
      var image = document.getElementById("flag");
      image.src = data[randomInt].image;
      flag = data[randomInt].name;
    });
  document.querySelector('.result').innerHTML = '';
  document.querySelector('.result').innerHTML = '';
}

function getAnswer() {
  document.querySelector('.result').innerHTML = flag;
  document.querySelector('.result').style.color = "white";
  document.querySelector('.next').disabled = true;
  document.querySelector('.skip').innerHTML = 'Drapeau suivant';
}

function skip() {
  getData();
  document.querySelector('.next').disabled = false;
  document.querySelector('.skip').innerHTML = 'Je passe';
  validateButton.addEventListener("click", getVal);
}

function next() {
  if (ans == true) {
    getData();
    inputValue = "";
  } else {
    document.querySelector('.result').innerHTML = 'Entrez la bonne réponse';
  }
  validateButton.addEventListener("click", getVal);
}
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600&display=swap" rel="stylesheet">
<script>
  window.onload = function() {
    getData();
    document.querySelector('.score').innerHTML = score;
  };
</script>

<h1>GuessTheFlag</h1>

<div >
  <div >
    <h3>Score : <span ></span></h3>
    <img width="100" id="flag" src="" alt="">
  </div>

  <div >
    <input type="text" name="flagName" placeholder="Nom du pays">
    <button type="submit" id="validate" >Je valide</button>
  </div>

  <p ></p>
  <p ></p><br>

  <div >
    <button onclick="next()" >Suivant</button>
    <button onclick="getAnswer()" >Réponse</button>
    <button onclick="skip()" >Je passe !</button>
  </div>

  <p>*Les réponses doivent être données en Anglais. <br>Pensez à valider votre réponse avant de passer à la suivante</p>
</div>

CodePudding user response:

The first idea that crosses my mind is a variable that is set to false, whenever you want to prevent users from a certain action.

var userCanClickAnswerButton = true;

When user clicks the button, the variable is set to false:

userCanClickAnswerButton = false;

So in the click event handler of the answer button you can insert this as first command:

if(!userCanClickAnswerButton) {
    return;
}

So the function will not execute any further commands when you don't want the user to click.

  • Related