ETAN
ETAN

Reputation: 3182

multilevel navigation children

I'm trying to slideup and slidedown, submenus inside a menu. A submenu can also contain submenu and so on.

Here's the html:

<ul class="nav">
  <li class="nav-parent"><a href="#">Level 1</a>
    <ul class="nav-child">
      <li class="nav-parent"><a href="#">Level 2</a>
         <ul class="nav-child">
            <li><a href="#">item</a></li>
            <li><a href="#">item</a></li>
            <li><a href="#">item</a></li>
         </ul>
      </li>
      <li><a href="#">some stuff</a></li>
      <li><a href="#">some stuff</a></li>
      <li><a href="#">some stuff</a></li>
    </ul>
  </li>
  <li><a href="#">some stuff</a></li>
  <li><a href="#">some stuff</a></li>
  <li><a href="#">some stuff</a></li>

</ul>

As you can see there are two submenus, nested submenus*

$('.nav-parent').on('click', function(){
    var me = $(this);
    if(me.hasClass('child-opened')){
        //child already opened > close
        me.find("> .nav-child").slideUp(200);
        me.removeClass('child-opened');
    } else {
        //child not opened > open
        me.find("> .nav-child").slideDown(200);
        me.addClass('child-opened');
    }
});

The jQuery works for first level, but does not work on second level. nav-child default is set to display:none in css.

Upvotes: 1

Views: 98

Answers (2)

Dmitry Zaets
Dmitry Zaets

Reputation: 3277

The problem is in bubbling of event.

There are tways to fix this:

  1. To return false / use event.stopPropagation(), here is working example.
  2. To use click event of anchor instead of click event on li element.

Upvotes: 1

Re Captcha
Re Captcha

Reputation: 3133

Just add a return false; at the end of your method: Demo

$('.nav-parent').on('click', function (event) {
    var me = $(this);
    if(me.hasClass('child-opened')){
        //child already opened > close
        me.find("> .nav-child").slideUp(200);
        me.removeClass('child-opened');
    } else {
        //child not opened > open
        me.find("> .nav-child").slideDown(200);
        me.addClass('child-opened');
    }
    return false;
});

Without the return false, it creates a bubbling of the event and calls the event for each of the parents.

To prevent event bubbling from the children, I added this:

$('.nav-child').on('click', function (event) {
    return false;
});

Upvotes: 2

Related Questions