open sub menu onclick and close opened sub menu

12.7k views Asked by At

I'm using a JS code to dispay sub menu from menu by clicking on li items. when I click on a li item, when sub menu slideToggle and if a sub menu is already openned then it's slideUp. It works perfectly.

But I have juste one issue, when clicking on a li from my sub menu, it slideUp and then SlideToggle again, how can I prevent this ?

Here is my jquery :

$("#menu li").click(function () {
    $('ul.sub-menu').not( $(this).children() ).slideUp();
    $(this).children("ul.sub-menu").slideToggle();
});

and here is what I've tried so far without success :

$("#menu li").not($('#menu li sub-menu li a')).click(function () {
    $('ul.sub-menu').not( $(this).children() ).slideUp();
    $(this).children("ul.sub-menu").slideToggle();
});

here is my html :

<ul id="menu">
<li><a href="#">1</a></li>
<li>2
<ul class="sub-menu">
<li><a href="#">2.1</a></li>
<li><a href="#">2.2</a></li>
</ul> 
</li>
<li>3
<ul class="sub-menu">
<li><a href="#">3.1</a></li>
</ul> 
</li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">6</a></li>
</ul>

and my CSS :

.sub-menu {display:none}

and a Jsfiddle to see it in action :

http://jsfiddle.net/2s023cfc/1/

can anybody help me with this ? thanks

2

There are 2 answers

2
Aramil Rey On

Specify the most to which element you are targeting the event in JQuery!

$("#menu > li > a").click(function () {
    $('ul.sub-menu').not($(this).siblings()).slideUp();
    $(this).siblings("ul.sub-menu").slideToggle();
});
.sub-menu {
    display:none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
    <li><a href="#">1</a></li>
    <li><a href="#">2</a>
        <ul class="sub-menu">
            <li><a href="#">2.1</a></li>
            <li><a href="#">2.2</a></li>
        </ul>
    </li>
    <li><a href="#">3</a>
        <ul class="sub-menu">
            <li><a href="#">3.1</a>
            </li>
        </ul>
    </li>
    <li><a href="#">4</a>
    </li>
    <li><a href="#">5</a>
    </li>
    <li><a href="#">6</a>
    </li>
</ul>

0
Manoz On

Try This-

  $("#menu li").not($('#menu li sub-menu li a')).click(function (e) {
        $('ul.sub-menu').not( $(this).children() ).slideUp();
        $(this).children("ul.sub-menu").slideToggle();
        e.stopPropagation()
    });

You need to stop propagation.