Search code examples
javascriptif-statementdomhide

how do I hide an element depending on the variable?


num=1
document.getElementById("Num").innerHTML = num
//button to increase/decrease num
function next() {
num++
document.getElementById("Num").innerHTML = num
}
function before() {
num--
document.getElementById("Num").innerHTML = num
}

//hide and show asdf
if (num=1){
document.getElementById("asdf").style.visibility = "hidden";
} else {
document.getElementById("asdf").style.visibility = "visible";
}
<div id="Num"></div>
<button onclick="before()">before</button>
<button onclick="next()">next</button>
<div id="asdf">asdf</div>

I want them to check num and hide or show asdf. I think that num variable is increasing/decreasing as I expected, but asdf isn't showing. I never used if statement out of function so maybe the problem is in there?


Solution

  • For starters, = is assignment and == is comparison. You're using the former, not the latter. That's an easily corrected typo. However, even with that the logic isn't running when you click the button.

    The difference is that the increase/decrease functionality is in the functions you're calling, whereas the show/hide functionality is not. That functionality only runs once when the page loads and then never again.

    You can wrap that functionality in a function and invoke it where you want. For example:

    num = 1;
    document.getElementById("Num").innerHTML = num;
    toggleVisible();
    
    //button to increase/decrease num
    function next() {
      num++;
      document.getElementById("Num").innerHTML = num;
      toggleVisible();
    }
    
    function before() {
      num--;
      document.getElementById("Num").innerHTML = num;
      toggleVisible();
    }
    
    //hide and show asdf
    function toggleVisible() {
      if (num == 1) {
        document.getElementById("asdf").style.visibility = "hidden";
      } else {
        document.getElementById("asdf").style.visibility = "visible";
      }
    }
    <div id="Num"></div>
    <button onclick="before()">before</button>
    <button onclick="next()">next</button>
    <div id="asdf">asdf</div>

    As an aside, I've added semi-colons to the lines of code. You'll definitely want to get in the habit of doing that. Automatic semi-colon insertion exists in JavaScript, but it's not something you should rely on all the time.