brittenb brittenb - 6 months ago 50
CSS Question

Toggle the display of a ul submenu only if parent li is clicked

I've looked through some of the other questions on this site that I thought might help, like this one and this one, but they don't seem to answer my question. What I have is the following:



$(document).ready(function() {
$(".has-submenu ul").hide();
$(".has-submenu").click(function() {
$(this).children("ul").toggle();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
<li><a href="#">Item 1</a></li>
<li class="has-submenu"><a href="#">Item 2</a>
<ul>
<li><a href="#">Sub Item 1</a></li>
</ul>
</li>
</ul>





As you can see from this snippet, the submenu is hidden regardless of whether I click "Item 2" or "Sub Item 1". I realize this is because "Sub Item 1" is part of the
<li class="has-submenu">
, so of course once it's clicked it goes through and toggles the sub menu. The CSS is doing what it's supposed to be doing, I just don't know how to tweak the CSS to say "Only hide the submenu if the parent
li
was clicked. I tried modifying the JQuery
click
function to look for
$(".has-submenu a")
to specify that it should only do that if that specific element was clicked, but that didn't seem to help.

I'm sure it's an easy fix, I just don't know how to do it. Thanks!

Answer

You can use $(".has-submenu > a") for click to select a that is direct child of .has-submenu only and then use next() to target ul

$(".has-submenu ul").hide();
$(".has-submenu > a").click(function() {
  $(this).next("ul").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Item 1</a></li>
  <li class="has-submenu"><a href="#">Item 2</a>
    <ul>
      <li><a href="#">Sub Item 1</a></li>
    </ul>
  </li>
</ul>