3

I'm trying to understand jQuery a little more, and today I'm attempting to play around with a menu structure. At present, my menu has three levels, and now I'm attempting to have the 'sub sub menu items' hidden until a visitor clicks on the second level of menu items.

My jQuery function to add and remove the 'nav-open' class works for the first and second level menu items, but I'm stuck on how to grow this function further to account for third level menu items, fourth, etc.

$(document).ready(function(){
 $('ul.nav li').click(function(){
  if($(this).hasClass('nav-open'))
   {    
     $(this).removeClass('nav-open');
   }
   else
    {
     $('ul.nav li').removeClass('nav-open');
    $(this).addClass('nav-open');
    }
 });

});

I've also tried my hand at the .toggleClass but that allows me to click on all main menu items without closing others, so right now I'm thinking this isn't the best approach.

$(document).ready(function(){
 $('ul.nav li').click(function(){
  $(this).toggleClass('nav-open');
  });
 });

My working demo is currently at jsFiddle and as you can see every time the submenu is opened, I immediately get my third level as well, but I'm looking to have these hidden until an individual clicks on a second level menu item.

Any help is appreciated!

1 Answer 1

1

You can use Toggle find() and first() to go deeper in your menu using many sub levels for example

  $('ul li a').click(function(){
     $(this).parent().find('ul').first().toggle();
  });

http://jsfiddle.net/sv27e/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Ninja, this has helped tremendously with my understanding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.