superartsy
superartsy

Reputation: 489

jquery simple collapsible list issue

I am trying to create a simple collapsible multi-level where each ul is collapsible. I am having a hard time figuring what I am doing wrong. my script is jsfiddle

<ul id="usernav">
<li>Manage
    <ul >
        <li >child11
         <ul>
             <li> some1</li>
             <li> some2</li>
         </ul>
        </li>
        <li>child12</li>
    </ul>
</li>
<li>Subscriptions
    <ul>
        <li>E-Briefings</li>
        <li>E-Briefings Subscriptions</li>
        <li>Knowledge Briefings</li>
    </ul>
</li>
  <li>Media Store
    <ul>
        <li>Image Store</li>
        <li>Document Store</li>
        <li>Media Store</li>
    </ul>
</li>

My script is

 $('#usernav').find('ul').hide();    
$('li').click(function() {
    $(this).children('ul').toggle();
});

Upvotes: 0

Views: 58

Answers (1)

Jason P
Jason P

Reputation: 27012

When you click the child of an element, you're also clicking the element. So when you click a child li, the event also fires on the parent lis. Use stopPropagation() to prevent the event from bubbling.

http://jsfiddle.net/nrVYn/

$('#usernav').find('ul').hide();

$('li').click(function(e) {
    $(this).children('ul').toggle();
    e.stopPropagation();
});

Upvotes: 2

Related Questions