0

I am trying to create a sidenav with menus and sub-menus. Sub-menu will shown on click of the parent menu. My approach is to use nested ul and set the height of sub-menu ul to 0; then add the height on click of parent menu with transition on height. But somehow the transition is not working. It takes 0.5 sec to change the height but its abrupt and now how we would like it to happen using transition. Link to jsfiddle

Here is sample code

document.querySelector('.has-sub').addEventListener('click', toggleSubmenu)

function toggleSubmenu() {
  let subMenu = document.querySelector(".sub-menu");
  subMenu.classList.toggle("show-submenu");
}
.navLinks {
  font-weight: 500;
  margin-top: 10%;
  width: 100%;
}

.navLinks ul {
  text-decoration: none;
}

.navLinks ul li {
  text-decoration: none;
  display: block;
  padding: 1em 0.5em;
  width: 100%;
  color: #132f63;
  cursor: pointer;
}

.navLinks ul li:hover {
  background-image: linear-gradient(to right, #dfe0fc, rgb(243, 243, 243));
}

.sub-menu {
  height: 0;
  -webkit-transition: height 0.5s;
  transition: height 0.5s;
  overflow: hidden;
  width: 100%;
  padding-left: 2em;
}

.sub-menu li {
  width: 100%;
}

.sub-menu li:hover {
  background-image: linear-gradient(to right, #d6d8ff, rgb(243, 243, 243));
}

.show-submenu {
  height: 100%;
}
<div class="navLinks">
  <ul>
    <li>Operations</li>
    <li class="has-sub">
      Service Analytics
      <ul class="sub-menu">
        <li>Incidents</li>
        <li>Problems</li>
        <li>Change Request</li>
        <li>Service Request</li>
      </ul>
    </li>

    <li>CIO</li>
    <li>Solarwinds</li>
  </ul>
</div>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
spark
  • 1,271
  • 1
  • 12
  • 18

1 Answers1

0

The problem you encounter is due to the fact that you can only animate height in pixel so your css need to be like

.sub-menu {
  height: 0px;
  -webkit-transition: height 0.5s;
  transition: height 0.5s;
  overflow: hidden;
  width: 100%;
  padding-left: 2em;
}

.show-submenu {
  height: 100px;
}

Or if the ul doesn't have a fix size

.sub-menu {
  height: 0px;
  -webkit-transition: height 0.5s;
  transition: height 0.5s;
  overflow: hidden;
  width: 100%;
  padding-left: 2em;
}

.show-submenu {
height: 100%;
  max-height: 500px;
}
  • Thanks for your answer.. This kind of question already been answered. It will be better to point the OP to that answer rather than answer another time. – Mosh Feu Jun 20 '19 at 16:39
  • @MoshFeu lol you get no rep points for that. _(this is a joke, I do agree with you)_ – zgood Jun 20 '19 at 16:56