James Bray James Bray - 8 months ago 35
HTML Question

Trying to Open/Close a div with one button

function openNav() {
document.getElementById("mySidenav").style.width = "200px";

/* Set the width of the side navigation to 0 */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";

<div onclick="openNav()" class="minimenubutton"><img src="images/menu.png"/></div>

I'm looking for a way to have the function change every time I click this so that I can open my div with one button. As of right now, I have closeNav set to a button inside that div, but I'd like to do it all with just the "minimenubutton."

I'm new to Javascript so please go easy on me. I looked up toggles but couldn't figure them out.


You just need one function with 2 conditionals (if and else);

function togNav() {
  var nav = document.getElementById("nav");
  if (nav.style.width == '200px') {
    nav.style.width = '0';
    nav.style.opacity = 0;
  } else {
    nav.style.width = "200px";
    nav.style.opacity = 1;
#nav {
  transition: opactity 3s ease-in;
  opacity: 0;
  cursor: pointer;
<p>Click under this paragraph</p>
<nav id="nav" onclick="togNav()" class="minimenubutton">
  <img src="https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" />