usman
usman

Reputation: 63

close and open button

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()">&#9776;</span>

and this is the button to close

<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>

Upvotes: 0

Views: 205

Answers (3)

Arun CM
Arun CM

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()">&#9776; CLICK</span>

<div id="mySidenav" style="background-color:blue;width:300px">
  <p>Some content.</p>
</div>

Upvotes: 0

Pranav C Balan
Pranav C Balan

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

Joschua Schneider
Joschua Schneider

Reputation: 4093

Without jQuery and any changes you want to make

You might wrap the openNavand 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

Related Questions