Search code examples
javascripthtmlcssresponsive-designnavbar

how to toggle my navbar to slide over in mobile view?


I want my navbar to slide over by clicking on its icon in mobile view, but I'm having some problems with that. It's not sliding over by clicking. I'm sure I have followed the right js syntax for it.

let navbar = document.querySelector(".navbar");
document.querySelector("#menu-btn").onclick = () => {
  navbar.classList.toggle("active");
}
.header .navbar {
  position: absolute;
  top: 100%;
  left: -100%;
  background: #13131a;
  width: 30rem;
  height: calc(100vh - 9.5rem);
  align-items: flex-start;
  flex-direction: column;
  justify-content: flex-start;
  overflow: hidden;
}

.header .navbar .active {
  left: 0;
}
<div class="navbar mx-auto ">
  <a asp-action="Index">صفحه اصلی</a>
  <a href="#products">محصولات</a>
  <a href="#about">درباره ما</a>
  <a href="#contact">ارتباط با ما</a>
</div>
<div class="icons">
  <i class="fa-solid fa-cart-shopping "></i>
  <i class="fa-solid fa-magnifying-glass "></i>
  <i class="fa-solid fa-right-to-bracket "></i>
  <i class="fa-solid fa-bars" `id="menu-btn"`></i>
</div>

I just don't know where I'm going wrong. the CSS class is changing when I click on the bar icon but not sliding over the navbar.


Solution

  • I think the main problem with your css is:

    .header .navbar .active {
      left: 0;
    }
    

    Since there is a space between .active it will look for an element inside the navbar div with the class active, but there isn't one.

    So instead this should be

    .header .navbar.active {
      left: 0;
    }
    

    Other minor things: id="menu-btn" had some backticks around it in your example which should be removed.

    You haven't included the header class in your example, but I think that should be ok as long as it's in an element wrapping everything.

    top:100% looks a bit odd, but maybe it's ok.