Reputation: 63
I want single button to open
and close
.
This is what I'm using for my side menu to close and open
:
function openNav() {
document.getElementById("mySidenav").style.width = "300px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
and this is the button open
<span class="collapses" style="font-size:30px;cursor:pointer;float:right;color:
#fff;margin-top: 20px" onclick="openNav()">☰</span>
and this is the button to close
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
Upvotes: 0
Views: 205
Reputation: 3435
Are you looking for something like this ?
function openNav() {
if (document.getElementById("mySidenav").style.width != "300px") {
document.getElementById("mySidenav").style.width = "300px";
} else {
document.getElementById("mySidenav").style.width = "0";
}
}
<span class="collapses" style="font-size:30px;cursor:pointer;float:right;color:
red;margin-top: 20px" onclick="openNav()">☰ CLICK</span>
<div id="mySidenav" style="background-color:blue;width:300px">
<p>Some content.</p>
</div>
Upvotes: 0
Reputation: 115212
Toggle the width based on current width value using a ternary operator.
function openNav() {
var div = document.getElementById("mySidenav");
div.style.width = div.style.width != '300px' ? "300px" : 0;
}
Upvotes: 2
Reputation: 4093
Without jQuery and any changes you want to make
You might wrap the openNav
and closeNav
calls into a third function that manages the open/close state.
function openNav(){...}
function closeNav(){...}
var isOpen = false;
function toggleNav(){
if(isOpen) {
closeNav();
isOpen = false;
}else{
openNav();
isOpen = true;
}
}
Then just call toggleNav()
on button click.
This lets you use any configuaration of style changes without using jQuery or checking for previous values.
Upvotes: 0