Search code examples
javascripthtmlcssdropdown

Dropdown mobile menu sliding in from top by pressing the Icon


I want my mobile dropdown menu to slide in from top when the user clicks the "header-downbar-menu" icon and slide out to the top when the user clicks it again. For now the button can only show the menu but I don't know how to properly write JS for this part...

var DropdownMenuDown = false;

function OpenDropdownMenu() {
  if (DropdownMenuDown == false) {
    document.getElementById("header-dropdown-menu").style.top = "0px";
  }
}
.header-dropdown {
  width: 100%;
  position: relative;
}

.header-dropdown-menu {
  width: 100%;
  height: 80vh;
  background-color: white;
  position: absolute;
  top: -80vh;
}
<div class="header-downbar-menu" onclick="OpenDropdownMenu()">
  <div class="bar1"></div>
  <div class="bar2"></div>
  <div class="bar3"></div>
</div>

<div class="header-dropdown">
  <div id="header-dropdown-menu" class="header-dropdown-menu">

  </div>
</div>

I can't make the var "DropdownMenuDown" work


Solution

  • I'd recommend you using toggle for this.

    Look here:

    function showMenu() {
      var topmenu = document.querySelector('.topmenu');
        topmenu.classList.toggle('show-me');
    }
    body {
      margin: 0;
    }
    
    #bg {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #AEAEAE;
    }
    
    .topmenu {
      position: absolute;
      height: 60px;
      top: -60px;
      width: 100%;
      background-color: red;
      z-index: 99;
    }
    
    .show-me {
      top: 0 !important;
    }
    
    
    button {
      position: absolute;
      top: 60px;
      left: 0;
    }
    <div id="bg">
      <div class="topmenu">
      </div>
      <button onclick="showMenu()">Menu pls!</button>
    </div>