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
Try the following:
So the idea is to hide everything but the clicked
li
, and then toggle subcategory visibility for the clicked one:Here is the jsFiddle with example.
Try this http://jsfiddle.net/7NYhe/