Search code examples
jquerymenu

Add more levels to expand/collapse jQuery menu


I want to use this expand/collapse jQuery menu on my website, but I need to nest more levels. This doesn't seem to be working by just nesting a to the sub-menu items I want to expand. Has anyone had any luck doing this?

Update: My code so far...

HTML

<div id='cssmenu'>
<ul>
   <li><a href='http://google.com'><span>Home</span></a></li>
   <li><a href='http://google.com'><span>Products</span></a>
      <ul>
         <li><a href='http://google.com'>Widgets</a></li>
         <li class="has-sub active"><a href='http://google.com'><span>Menus</span></a>
            <ul>
               <li><a href='http://google.com'>Widgets</a></li>
               <li><a href='#'>Menus</a></li>
               <li><a href='#'>Products</a></li>
            </ul>
         </li>
         <li><a href='#'>Products</a></li>
      </ul>
   </li>
   <li><a href='#'><span>Company</span></a>
      <ul>
         <li><a href='#'>About</a></li>
         <li><a href='#'>Location</a></li>
      </ul>
   </li>
   <li><a href='#'><span>Contact</span></a></li>
</ul>
</div>

jQuery

$(document).ready(function(){

  $('#cssmenu > ul > li:has(ul)').addClass("has-sub");

  $('#cssmenu > ul > li > a').click(function() {
    var checkElement = $(this).next();

    $('#cssmenu li').removeClass('active');
    $(this).closest('li').addClass('active');   


    if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
      $(this).closest('li').removeClass('active');
      checkElement.slideUp('normal');
    }

    if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
      $('#cssmenu ul ul:visible').slideUp('normal');
      checkElement.slideDown('normal');
    }

    if (checkElement.is('ul')) {
      return false;
    } else {
      return true;  
    }       
  });

});

Solution

  • Here is a Fiddle

    Added one more if condition and an extra check in all the others if it has the class sub-sub-menu

    && (!checkElement.hasClass('sub-sub-menu'))