user4103074
user4103074

Reputation: 15

Add dropdown toggle to ul.submenu

I would like to add a simple toggle for sub-menu class. I am not sure what is wrong with the code.

$(document).ready(function() {
  $("ul .sub-menu").parent().closest("li").append('<span class="submenu-toggle">▼</span>');
  $("ul .sub-menu").hide();
  $(".submenu-toggle").click(function() {
    $(this).children("ul .sub-menu").toggle();
    $(this).html('▲');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul class="nav-menu">
  <li></li>
  <li>
    <ul class="sub-menu">
      <li>Sub-item</li>
      <li>Sub-item</li>
    </ul>
  <li></li>
</ul>

Thanks!

Upvotes: 1

Views: 42

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because .sub-menu is a sibling of the span that's clicked, so you need to use siblings(), not children(). Also, you can just use closest() alone instead of parent().closest(). Try this:

$(document).ready(function() {
  $("ul .sub-menu").hide().closest("li").append('<span class="submenu-toggle">▼</span>');

  $(".submenu-toggle").click(function() {
    $(this).siblings(".sub-menu").toggle();
    $(this).html(function(i, h) {
      return h == '▲' ? '▼' : '▲';
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul class="nav-menu">
  <li></li>
  <li>
    <ul class="sub-menu">
      <li>Sub-item</li>
      <li>Sub-item</li>
    </ul>
    <li></li>
</ul>

Also note that I included the logic which toggles the arrow based on the state of the menu.

Upvotes: 1

Related Questions