pnichols
pnichols

Reputation: 2278

Weird problem with jQuery toggle..?

I have a menu/UL with a bunch of LI, and inside those LI, I've got some more UL, LI... Have a look:

<ul class='parent'>
  <li><a>Boules</a></li>
  <li>
    <a>Livres</a>
    <ul class='child'>    
      <li><a>Magazines</a></li>
      <li><a>Revues</a></li>
      <li><a>Romans</a></li>
    </ul>
  </li>
  <li>
    <a>Wirelace (3 childs)</a>    
    <ul class='child'>
      <li><a>Bleu</a></li>
      <li>
        <a>Rouge</a>
        <ul class='subchild'>
          <li><a>4mm</a></li>
          <li><a>6mm</a></li>    
        </ul>
      </li>
      <li>
        <a>Vert</a>
        <ul class='subchild'>
          <li><a>2mm</a></li>
          <li><a>4mm</a></li>    
          <li><a>6mm</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

All UL .child and .subchild are hidden with CSS display:none; so what you see when you load the page is just the 3 LIs of class PARENT (Boules, Livres, Wirelace).

I've got this jQuery code (works as expected) to toggle the display of UL .child, when clicked the LI show up, but the subchild UL stay hidden, as expected:

$("ul.parent li a").click(function() { 
    $(this).next().toggle(); 
    return false;
});

I also have this one for UL .subchild, but it doesn't work, even if it's identical:

$("ul.child li a").click(function() { 
    $(this).next().toggle(); 
    return false;
});

It works as expected if I do:

$(this).next().toggle().toggle();

If I use just 1 toggle, it plays with the display (I see it in Firebug), but if it's hidden (by the original CSS), it adds display:none. If I remove the CSS (making it visible on page load), it adds display:block.

The only way it acts as expected, is if I force it with show() or hide(). But then I don't have toggle feature.

Even an if($(this).is("visible")) won't work...

That's in Firefox, Chrome, Safari, IE8.

I'm sorry for the long post, anyone has an idea what might cause that...???

Upvotes: 1

Views: 241

Answers (1)

Yi Jiang
Yi Jiang

Reputation: 50095

The problem is that the selector

ul.parent li a

in fact is general enough to also select ul.child li a, so the elements under .child actually have both handlers attached to them. If you would just make the selectors a bit more specific, you can avoid this problem.

ul.child > li > a, ul.parent > li > a

Also try using the child selector, ul > li > ul instead of giving them classes to indicate that they are children.

Upvotes: 1

Related Questions