omid mirzaei
omid mirzaei

Reputation: 35

jQuery dropdown menu toggle issue

When I click on open it toggles all of the submenus. I want to toggle only the exact ul under the li.

$(document).ready(function(){
    $(".has-children>a").click(function(event){
        event.preventDefault();
    });
    $('.has-children').click(function() {
        $(this).find('>ul').toggle(300);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
    <li class="has-children">
    <a href="#">open</a>
        <ul class="submenu" style="display:none">
            <li class="has-children">
            <a href="#">open</a>
                <ul class="submenu" style="display:none">
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </li>
        </ul>

    </li>
</ul>

Upvotes: 0

Views: 50

Answers (1)

Frits
Frits

Reputation: 7614

You can achieve this by changing find() to children() to target only direct children of the li.

$(document).ready(function(){
    $(".has-children>a").click(function(event){
        event.preventDefault();
    });
    $('.has-children').click(function() {
        $(this).children('ul').toggle(300);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
    <li class="has-children">
    <a href="#">open</a>
        <ul class="submenu" style="display:none">
            <li class="has-children">
            <a href="#">open</a>
                <ul class="submenu" style="display:none">
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </li>
        </ul>

    </li>
</ul>

This however causes a problem where clicking on children of children will close the menu, so instead you can use a tag and the jQuery next() function to toggle instead of children() or find() like this:

$(document).ready(function() {
  $(".has-children>a").click(function(event) {
    event.preventDefault();
    $(this).next().toggle(300);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
  <li class="has-children">
    <a href="#">open</a>
    <ul class="submenu" style="display:none">
      <li class="has-children">
        <a href="#">open</a>
        <ul class="submenu" style="display:none">
          <li>1</li>
          <li>2</li>
          <li>3</li>
        </ul>
      </li>
    </ul>

  </li>
</ul>

This also makes your script much shorter.

Upvotes: 2

Related Questions