skip to Main Content

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 ?

3

Answers


  1. Try the following:

    $('li.dropdown').click(function() {
       $(this).find('ul').toggle();
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. $('li.dropdown').click(function() {
       $('.dropdown ul').hide();
        $(this).children('ul').show();
    });
    

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search