Reputation: 171
Having a few issues with my javascript code to toggle the opening and closing of a mobile menu. The below code works for opening the menu = style.height: 200px, but once the menu is open, clicking on the button doesn't close the menu bar (style.height: 0) as expected.
Anyone have some pointers as too where i'm going wrong with my code?
document.getElementById("hamburger").addEventListener("click", toggleNav);
function toggleNav(){
navSize = document.getElementById("mobilemenu").style.height;
if (navSize == 200) {
return close();
}
return open();
}
function open() {
document.getElementById("mobilemenu").style.height = "200px";
}
function close() {
document.getElementById("mobilemenu").style.height = "0";
}
<div class="menubutton">
<button id="hamburger" class="hamburger hamburger--collapse" type="button" onclick="toggleNav()">
<span class="hamburger-box">
<span class="hamburger-inner"></span>
</span>
</button>
</div>
Upvotes: 1
Views: 140
Reputation: 2575
you can simply do that using classList.toggle
document.getElementById("hamburger").addEventListener("click", function (e) {
e.preventDefault();
document.getElementById("mobilemenu").classList.toggle('show');
});
.menubutton {
position: fixed;
top:10px;
left:10px;
z-index: 999;
}
#mobilemenu {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: 200px;
transform: translateX(-100%);
border-right: 1px solid #ccc;
background-color: #eee;
transition: transform .3s ease;
}
#mobilemenu.show {
transform: translateX(0);
}
<div class="menubutton">
<button id="hamburger" class="hamburger hamburger--collapse" type="button">
<span class="hamburger-box">
<span class="hamburger-inner">Click</span>
</span>
</button>
</div>
<div id="mobilemenu"></div>
Upvotes: 1
Reputation: 4435
You're testing for the wrong value in toggleNav()
Use if (navSize == "200px")
Upvotes: 3
Reputation: 1898
this is the faulty code:
if (navSize == 200) {
return close();
}
return open();
navSize will be something like "200px"
, not 200
Since the if statement is always false, it only runs open()
Upvotes: 0