Search code examples
jqueryhtmlcsstoggleclass

Why is this simple jQuery toggle not working?


I am wondering why this toggle is not working. The addClass method and therefore hiding the nav is working well... Is there a simple typo I am missing or am i getting the concept wrong? Thanks for support.

$(document).ready(function() {
  $("body").addClass("js");

  var $menu = $("#menu"),
    $menulink = $(".menu_link");

  $menulink.click(function() {
    $menulink.toggleClass("active");
    $menu.toggleClass("active");
    return false;
  });
});
.menu_link {
  position: absolute;
  top: 1.5rem;
  right: 1.5rem;
  color: black;
  background-color: #fff;
  padding: 1rem;
  border-radius: 50%;
}
.menu_link .active {
  background-color: red;
}
.js nav {
  overflow: hidden;
  max-height: 0;
}
nav .active {
  max-height: 15rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#menu" class="menu_link">Inhalt</a>
<nav id="menu">
  <ul>
    <li><a href="#">Punkt 1</a></li>
    <li><a href="#">Punkt 2</a></li>
    <li><a href="#">Punkt 3</a></li>
    <li><a href="#">Punkt 4</a></li>
  </ul>
</nav>

Solution

  • The error is in your CSS; the .active class is placed directly on the nav and .menu_link elements so you need to remove the spaces between their selectors:

    .menu_link.active {
        background-color: red;
    }
    
    nav.active {
        max-height: 15rem;
    }
    

    Working example