views:

84

answers:

2

I'm using jQuery for a vertical site navigation menu, all links within site. I have the basic functionality working, but am at a loss as to the correct if-else to accomplish the following:

As the code stands, the submenu items are always initially hidden, but I want them to start shown if the user-selected li or one of its child lis is assigned the class currentpage. The code as it stands is:

(function(){
  $('li:has(ul)')
  .click(function(event){
    if (this == event.target || $(event.target).parent()[0] == this) {
      if ($(this).children('ul').is(':hidden')) {
        $(this)
        .css('list-style-image','url(minus.gif)')
        .children('ul').slideDown();
      }
      else {
        $(this)
       .css('list-style-image','url(plus.gif)')
       .children('ul').slideUp();
      }
    }
  })
  .css({
    cursor:'pointer',
    'list-style-image':'url(plus.gif)'
  })
  .children('ul').hide();

  $('li:not(:has(ul))').css({
    cursor: 'default',
    'list-style-image':'none'
  });
});

Hopefully someone can put me on the right track.

Bob McLeod

A: 

I would make a showMenuItem() function and call it in both places where you want to show a menu item.

$(function() { $('.currentpage').each(function() {
  if ($(this).parents().filter('ul').is(":hidden")) {
    showMenuItem($(this).parents().filter('ul'));
  } else {
    showMenuItem(this);
  }
}});
Jack M.
why not do the .css() and .children('ul') on $('.currentpage') itself instead of the each()?
Brandon H
Whenever I'm working with a class, I assume that there may, at some point in the future, be more than one of them. If it were #currentpage, I wouldn't use the .each().
Jack M.
but $('.currentpage').css() will already change the css for all the elements with class=currentpage
Brandon H
Oh, well then. I thought it returned a list.
Jack M.
+1  A: 

I want them to start shown if the user-selected li or one of its child lis is assigned the class currentpage.

How about afterwards doing:

$('.currentpage').parents('ul').show();
bobince