Hennessey Hennessey - 2 months ago 18
HTML Question

Using jQuery(this).next() to show/hide the next nested UL in a menu

Whenever "section" is clicked, I would like for the next UL (sub-menu) to disappear (or reappear). I can get a simple P tag to disappear outside of this tree, but I am trying to use the jQuery next(); function. How can I select this element with jQuery. I thought that:

$(".section").click(function() {
$(this).next('ul').hide();
});


Would work, but it doesn't... here is the HTML:

<div class="menu">
<ul class="main-menu">
<li class="section">
Section 1
<ul class="sub-menu" style="z-index: 3;">
<li>
Section 1A
</li>
<li>
Section 1B
</li>
<li>
Section 1C
</li>
<li>
Back
</li>
</ul>
</li>
<li class="section">
Section 2
<ul class="sub-menu" style="z-index: 2;">
<li>
Section 2A
</li>
<li>
Section 2B
</li>
<li>
Section 2C
</li>
<li>
Back
</li>
</ul>
</li>
</ul>
</div>


Update

Find() worked fine. But now I am wondering how I can use the li element with the text "Back" in it to toggle the sub-menu off. I have added a class "back" to the last LI element on each sub-menu list, but jQuery can't seem to find it and apply the CSS. Here is what I have:

//this code works
$(".section").click(function() {
$(this).find('ul').css( "left", "0" );
});

//this code doesn't locate the previous UL (i also tried (".sub-menu").css()
$('.back').click(function() {
$('.back').prev('ul').css( "left", "485" );
});

//html:

<li class="section">
Section 1
<ul class="sub-menu" style="z-index: 3;">
<li>
<a href="#section1a">Section 1A</a>
</li>
<li>
<a href="#section1b">Section 1B</a>
</li>
<li>
<a href="#section1c">Section 1C</a>
</li>
<li class="back">
<a href="#back">Back</a>
</li>
</ul>
</li>

Answer

In your code you use next() which looks at the next sibling, where you instead want to look at the children. To target them, you can use the find(filter) function. By finding the ul, you can use toggle() or slideToggle to toggle it's visibility.

I've also added an extra click function on the children. That prevents that clicking the child closes the sub-menu.

$(function() {
  $('.section').click( function() {
    $(this).find('ul').slideToggle();
  }).children().click( function() {
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <ul class="main-menu">
    <li class="section">
      Section 1
      <ul class="sub-menu" style="z-index: 3;">
        <li>Section 1A</li>
        <li>Section 1B</li>
        <li>Section 1C</li>
        <li>Back</li>
      </ul>
    </li>
    <li class="section">
      Section 2
      <ul class="sub-menu" style="z-index: 2;">
        <li>Section 2A</li>
        <li>Section 2B</li>
        <li>Section 2C</li>
        <li>Back</li>
      </ul>
    </li>
  </ul>
</div>

Comments