How do I toogle sidebars?

Viewed 34

I've got a sliding panel which I want to hide in push.
Now I've got two links, one for show and another for hide:

function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}

How can I do it in one function ?

2 Answers

The short answer

Below is a simple way to do it with minimal change from your code:

function toggleNav() {
  if (document.getElementById("mySidenav").style.width === "0") {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
  } else {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft = "0";
  }
}



A better approach using CSS

This approach will greatly reduce the complexity of the JS. If you attached a nav-open class to a parent container such as the document body.

JS

function toggleNav() {
    document.body.classList.toggle('nav-open');
}

CSS

.nav-open #mySidenav {
  width: 250px;
}

.nav-open #main {
  margin-left: 250px;
}

You can do this with a variable like so:

var navIsOpen = false;

function toggleNav() {
  if (navIsOpen) {
    // Close
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
  } else {
    // Open
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
  }

  navIsOpen = !navIsOpen;
}
Related