2

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!

1 Answer 1

5

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:

<div id="menu">
    <ul>
        <li><a id="database" href="#">Database</a>            
            <ul>
                <li><a href="#">view database</a></li>
                <li><a href="#">edit database</a></li>
            </ul>
        </li>

        <li><a id="production" href="#">Production</a>
            <ul>
                <li><a href="#">add order</a></li>
                <li><a href="#">plan orders</a></li>
            </ul>
        </li>
    </ul>
</div>

After that, you just need to stop the click event from bubbling up to the parent <li>, like this:

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

You can test it out here.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks! I was suspicious about my list mark-up, thanks for pointing that out. Also, thanks for pointing me towards JSFIDDLE, looks very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.