Solution 1 :

Try this, the logic is: x equals 0 ? then x = 1 else x = 0.

var x = 0;

function tog() {

x = x == 0 ? 1 : 0;

    if (x == 0) {
        console.log(x)
    } else if(x == 1){
        console.log(x)
    }

};
<div class="panel"><button class='pan' onclick='tog()'>Toggle!</button></div>

Solution 2 :

You could do something like this.

var x = 0;

function toggle() {
  if (x === 0) {
    document.getElementById("Sidenav").style.height = "150px";
    document.body.style.backgroundColor = "rgba(0,0,0,1)";
    x = 1;
  } else {
    document.getElementById("Sidenav").style.height = "0";
    document.body.style.backgroundColor = "white";
    x = 0;
  }
  
};
#Sidenav {
  width: 400px;
  border: 1px solid #9c0000;
  border-radius: 10px;
  height: 0;
}
<div id="Sidenav"></div>
<button onclick="toggle()">toggle</button>

Solution 3 :

let sideNav = document.getElementById("Sidenav");
function toggle(){
    sideNav.classList.toggle("open");
    document.body.classList.toggle("open-bg");
}


.open{
    height: 450px;
}

.open-bg{
    background-color: rgba(0, 0, 0, 1);
}

make use of toggle method for classList to remove and add class alternately when button is clicked.

and try not to change css attributes too much in JavaScript. I mean it’s not bad but it makes your code look kinda big.

Problem :

I am trying to make a toggle button on a website that I am making that activates a javascript navbar when pressed then when pressed a second time the navbar retracts out of sight. I have got the code working to where the navbar pops out when the button is pressed but I can’t work out how to make the navbar retract.

function tog() {

  var x = 0;
  
  if (x == 0) {
    document.getElementById("Sidenav").style.height = "450px";
    document.getElementById("main").style.marginTop = "0px";
    document.body.style.backgroundColor = "rgba(0,0,0,1)";
    x = 1;
  }
  
  else {
    document.getElementById("Sidenav").style.height = "0";
    document.getElementById("main").style.marginTop= "0";
    document.body.style.backgroundColor = "white";
    x = 0;
  }
  
};

This is the javascript that controls the toggle function, and the button is:

<div class="panel"><button class='pan' onclick='tog()'></button></div>

Any input as to where I am going wrong would be much appreciated.

Comments

Comment posted by charlietfl

Since you declare

Comment posted by invisabuble

Hey thanks this works great, i did add: onload=”tog()” to the body tag to make it work when i first click it instead of having to click it 3 times.

By