OneMoreError
OneMoreError

Reputation: 7728

Hiding and showing <ul> and <li> on click using Javascript

I need to show a few categories on my web page and their sub-categories as well. So I have arranged them in the form of nested <ul> <li> tags. I want the effect that only when a user clicks on one of the categories, all the sub-categories should become visible. Initially no sub-categories are visible.


In the body part, I have done this

<ul>
   <li class="dropdown">Data mining and data warehousing
      <ul>
           <li>Data mining techniques</li>
           <li>Knowledge discovery</li>
      </ul>
   </li>

    <li class="dropdown">Soft computing and artificial intelligence
       <ul>
            <li>Fuzzy systems</li>
            <li>Neural networks</li>
       </ul>
    </li>
</ul>

In the css part, I have done

li.dropdown ul {
display : none;
}

And I have added the following Javascript script in the head section of the html page

<script type="text/javascript">
$('li.dropdown').click(function() {
   $(this).children('ul').toggle();
});
</script>

Initially, the effect works fine and all the sub categories are hidden. However, I want, say when I click on Data mining and data warehousing, then the two sub-categories should also become visible, which are Data mining techniques and Knowledge discovery.


Also, when I click on other category, the sub-categories of previously opened categories should collapse again. How can I do that ?

Upvotes: 0

Views: 23414

Answers (3)

Andrei
Andrei

Reputation: 56688

So the idea is to hide everything but the clicked li, and then toggle subcategory visibility for the clicked one:

$('li.dropdown').click(function() {
   $('li.dropdown').not(this).find('ul').hide();
   $(this).find('ul').toggle();
});

Here is the jsFiddle with example.

Upvotes: 11

Amit Garg
Amit Garg

Reputation: 3907

$('li.dropdown').click(function() {
   $('.dropdown ul').hide();
    $(this).children('ul').show();
});

Try this http://jsfiddle.net/7NYhe/

Upvotes: 1

janhenkes
janhenkes

Reputation: 107

Try the following:

$('li.dropdown').click(function() {
   $(this).find('ul').toggle();
});

Upvotes: 1

Related Questions