jquery problem with toggle event only fireing on the 2nd click...

Posted by Ronedog on Stack Overflow See other posts from Stack Overflow or by Ronedog
Published on 2010-03-29T21:40:49Z Indexed on 2010/03/29 21:43 UTC
Read the original article Hit count: 149

Filed under:
|

Can anyone explain why the following jquery only fires the 2nd toggle event and how to fix it? Specifically, every time I click the nested < a > element it brings up the alert "2nd click".

I tested the selector to make sure it was selecting the element properly and it does, or at least it inserted a class without any problems.

The selector is selecting the very last node in the unordered list that has an anchor tag.

$("#nav li:not(:has(li)) a").toggle(function() { //1st click
              alert("1st Click");
        }, function() { //2nd click
            alert("2nd Click");
        });

Nested HTML structure that fails:

<ul id="nav">
    <li>
      <span>stuff</span>
      <a href="#">Cat 1</a>
        <ul>
           <li>
               <span>stuff</span>
               <a href="#">Subcat1</a>
                 <ul>
                    <li>
                       <span>Stuff</span>
                       <a href="#">Subcat Details</a>
                    </li>
                 </ul>
           </li>
        </ul>
    </li>
</ul>

However, this works right and fires both click events:

<ul id="nav">
    <li>
      <span>stuff</span>
      <a href="#">Cat 1</a>
    </li>
</ul>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-selectors