0
var x; 

function apply() {
    if (x = 1) {
        alert("show");
        document.getElementById("nav").style.display = "inline";
        var x = 2;
    } else {
        alert("hide");
        document.getElementById("nav").style.display = "none";
        var x = 1;
    }
}

function hide() {
    document.getElementById("nav").style.display = "none";
    x = 1;
    alert(x)
}

I am having some trouble with this piece of code. I use the function hide onload and have function apply linked to a button click.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299

2 Answers2

5

Correct usage:

var x; // we define the variable x global outside the functions

function apply() {
    if (x == 1) { // you need to check with ==, with = you are just setting its value
        alert("show")
        document.getElementById("nav").style.display = "inline";
        x = 2 // change the varibale to 2
    } else {
        alert("hide")
        document.getElementById("nav").style.display = "none";
        x = 1 // change it to 1
    }

}

function hide() {
    document.getElementById("nav").style.display = "none";
    x = 1;
    alert(x)
}
juvian
  • 15,875
  • 2
  • 37
  • 38
0

You cant define both outside from if and inside of if. You should remove 'var' from inside of if

  • You can, it's just that the one inside has a different scope. Its worth explaining fully, as a one line answer is rarely judged as good. – Jamiec Nov 25 '14 at 16:37