Home > Net >  Hiding a button until a condition is met (Javascript)
Hiding a button until a condition is met (Javascript)

Time:12-15

I am making a fishing game, where I want a button to be hidden until the fish number reached 5. However, the button (set fish traps) does not seem to be hidden even the condition has been met...

let fishNum = document.getElementById("fishNum");
let traps = document.getElementById("cm2Btn2");

function addFish() {
  let fishNum = document.getElementById("fishNum");

  count.innerHTML  ;
}

if (fishNum > 2) {
  traps.classList.add('fadeOut');
}
<div >
  <span id="fishNum">0</span>
</div>

<button id="cm2Btn" onclick="document.getElementById('fishNum').innerHTML  ">Catch a Herring</button>

<button id="cm2Btn2">Set Fish Traps</button>

CodePudding user response:

Your example only checks the value of fishNum on the initial load, and fishNum is not a number but an element from the dom. Your addFish function is never used, only the inline js from the html. Your addFish function increments a variable called count, which is never defined. There is no css for the class fadeOut so the item will not fade out even if the class were added.

Please see my demo, which is a rough fix of what you were attempting to do. Some things that I would change moving forward, instead of incrementing the HTML of fishNum, I would have a variable in js that you increment, and update the screen to reflect what is happening in your js.

At the core of answering this question, I believe you are looking for the css property transition and the html attribute disabled. We can use js to enable the button when we add the fadeIn class, and make it so we transition gradually from 0 to 1 opacity.

let fishNum = document.getElementById("fishNum");
let traps = document.getElementById("cm2Btn2");

function addFish() {
  fishNum.innerHTML  ;
  
  if (fishNum.innerHTML > 4) {
    traps.classList.add("fadeIn");
    traps.disabled = false;
  }
  
}
document.getElementById("cm2Btn")
  .addEventListener("click", addFish);
#cm2Btn2 {
  transition: opacity 1s;
  opacity: 0;
}

#cm2Btn2.fadeIn {
  opacity: 1;
}
<div >
  <span id="fishNum">0</span>
</div>

<button id="cm2Btn">Catch a Herring</button>

<button disabled="true" id="cm2Btn2">Set Fish Traps</button>

  • Related