Reputation: 311
I have this code where this silver block on click should toggle the navigation bar. It does trigger once and does not for the second try to toggle the navigation bar back. I am assuming this code has some minor bug and I could not find what.
Here is the code.
function toggleNav() {
var navStatus = true;
if (navStatus == true) {
document.getElementById("closenav").style.left = "-300px";
navStatus = false;
} else if (navStatus == false) {
document.getElementById("closenav").style.left = "0px";
navStatus = true;
}
}
nav {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
width: 300px;
background-color: #272727;
transition: all ease-in-out 200ms;
}
nav div {
position: fixed;
top: 40px;
left: 40px;
width: 60px;
height: 60px;
background-color: silver;
}
<nav id="closenav">
<div onclick="toggleNav()"> </div>
</nav>
Upvotes: 1
Views: 42
Reputation: 16855
You will need to define you variable var navStatus = true
outside the toggleNav()
function otherwise your variable navStatus
value will be always true
on every click as it is stated at the first line of your function...Also just use else
instead of else if
var navStatus = true;
function toggleNav() {
if (navStatus == true) {
document.getElementById("closenav").style.left = "-300px";
navStatus = false;
} else {
document.getElementById("closenav").style.left = "0px";
navStatus = true;
}
}
nav {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
width: 300px;
background-color: #272727;
transition: all ease-in-out 200ms;
}
nav div {
position: fixed;
top: 40px;
left: 40px;
width: 60px;
height: 60px;
background-color: silver;
}
<nav id="closenav">
<div onclick="toggleNav()"> </div>
</nav>
Upvotes: 2