I have a problem that I’m sure is very simple, yet I have spent hours trying to get it to work to no avail.
I am trying to display a nested list whenever a parent list item is clicked.
This is the JQuery:
<script type="text/javascript">
$(document).ready(function() {
$("#menu ul ul" ).hide();
$("#menu ul li").click(function() {
$(this).next().toggle();
});
});
</script>
and this is the HTML:
<div id="menu">
<ul>
<li><a id="database" href="#">Database</a></li>
<ul>
<li><a href="#">view database</a></li>
<li><a href="#">edit database</a></li>
</ul>
<li><a id="production" href="#">Production</a></li>
<ul>
<li><a href="#">add order</a></li>
<li><a href="#">plan orders</a></li>
</ul>
</ul>
</div>
Now When I click the fisrt ul li’s the correct nested list toggles, however when I click the nested li’s they too toggle. It must be something to do with the way I am selecting the first nested list…
Any help is much appreciated!
First, let’s get some valid markup, the
<ul>elements can’t be direct children of another<ul>, they should be inside a<li>, like this:After that, you just need to stop the
clickevent from bubbling up to the parent<li>, like this:You can test it out here.