urosv
urosv

Reputation: 63

JS if else statement and a reset

I want to prevent any actions if the button attack is not clicked. In this case i want to prevent If attack is clicked you can click on send troops, else alert('You need first to attack!'). Also when the time runs out, i want to the clock disappear if that is possible.

Clock

   <button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>
<button class="troops" onclick="send()">SEND TROOPS</button>

JS

function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}

Upvotes: 0

Views: 516

Answers (3)

Naruto
Naruto

Reputation: 708

you can add "disabled" attribute to "SEND TROOPS" button at first, it will disable this button which will prevent clicking it. you can remove that attribute when "ATTACK" is clicked.

Add attribute

document.getElementsByClassName("troops")[0]).setAttribute("disabled","disabled")

Remove attribute:

document.getElementsByClassName("troops")[0]).removeAttribute("disabled","disabled")

Upvotes: 1

dennispreston
dennispreston

Reputation: 606

Do you mean something like this?

function startTimer(duration, display) {

  // Make troops button enabled when attack button is clicked
  document.getElementsByClassName("troops")[0].removeAttribute("disabled");

  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}
<button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>

<!-- declare troops button disabled before attack has been clicked -->
<button class="troops" disabled onclick="send()">SEND TROOPS</button>

Upvotes: 0

Pratyush Sharma
Pratyush Sharma

Reputation: 257

You can have a global flag (say isAttacked) which will store whether the attacked button is clicked. Then in the send function check for isAttacked variable and if it's true send the troops.

Upvotes: 0

Related Questions