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?
3
Answers
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:
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.
Use a setState function for setting the visible num value and for showing/hiding asdf