Chrono124
Chrono124

Reputation: 35

Closing previous items in jQuery Menus

First time posting here, but I always come here first when researching. Anyways I have searched everywhere and can't find a solid solution to my problem. Here is the issue, I have created a vertical sliding menu with jQuery 1.9.1 and the slideToggle function. I have put an example in a jsFiddle http://jsfiddle.net/JWaXM/1/

<li class="topnav"><a href="#">ITEMS LIST 1</a>
<ul>
    <li class="subnav">ITEM 1
        <ul>
            <li>List subitem 1</li>
            <li>List subitem 2</li>
        </ul>
    </li>
    <li class="subnav">ITEM 2
        <ul>
            <li>List subitem 1</li>
            <li>List subitem 2</li>
        </ul>
    </li>
 </ul>
</li>

<li class="topnav"><a href="#">ITEMS LIST 2</a>
<ul>
    <li class="subnav">ITEM 1
        <ul>
            <li>List subitem 1</li>
            <li>List subitem 2</li>
        </ul>
    </li>
    <li class="subnav">ITEM 2
        <ul>
            <li>List subitem 1</li>
            <li>List subitem 2</li>
        </ul>
    </li>
 </ul>
</li>

<script type="text/javascript">
$(document).ready(function(){
$(".topnav, .subnav").click(function(event){
 event.stopPropagation();
 $(this).children("ul").slideToggle();
});
});
</script>

The menu works great, but I need to figure out how to close the previous child menu when I open another. Also, I need a way to distinguish between parent and child so it will know to either close a topnav or subnav. I am new to the whole jQuery thing, but I am slowly learning. Thanks for any help I appreciate it.

Upvotes: 1

Views: 257

Answers (2)

billyonecan
billyonecan

Reputation: 20260

You could slide up all of the children of the clicked elements siblings:

$(this).siblings().children('ul').slideUp();

That way you don't need to know if the element clicked was a topnav or subnav element, and it will support as many nested <ul>'s as necessary

Demo

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

Try

$(document).ready(function(){
    $(".topnav, .subnav").click(function(event){
        event.stopPropagation();
        $(this).closest('ul').find('.active').stop().slideToggle().removeClass('active');
        $(this).children("ul").slideToggle().addClass('active');
    });
});

Demo: Fiddle

Upvotes: 0

Related Questions