Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery show submenu if parent have been clicked

Could some one please help with code.

I want to show the submenu only when submenu parent is clicked.

HTML

<ul>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
    <ul class="sub-menu">
        <li><a href="#">Submenu</a></li>
        <li><a href="#">Submenu</a></li>
    </ul>
</li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
    <ul class="sub-menu">
        <li><a href="#">Submenu</a></li>
        <li><a href="#">Submenu</a></li>
    </ul>
</li>
<li><a href="#">Item</a></li>
</ul>

So if you click on the parent submenu will show.

Here is fiddle link - http://jsfiddle.net/KhNCV/1/

like image 530
iKaspars Avatar asked Nov 22 '11 18:11

iKaspars


3 Answers

$('.sub-menu').hide();

$("li:has(ul)").click(function(){

$("ul",this).slideDown();
});

http://jsfiddle.net/3nigma/KhNCV/2/

OR

$('.sub-menu').hide();

$("li:has(ul)").click(function(){

$("ul",this).toggle('slow');
});

http://jsfiddle.net/3nigma/KhNCV/4/

like image 125
Rafay Avatar answered Oct 19 '22 00:10

Rafay


Here's your example working. It's unclear why you need the a tags, as you could use cursor: pointer in the CSS to make the li appear clickable. I'll assume you want to do some spiffy hovering on them in IE that's CSS only? If not, you could simplify by removing them.

Instead of doing hide() on .submenu, you should use CSS (parsed with DOM instead of onReady/load).

.sub-menu { display: none; }

And then here's you code to toggle the menus:

$('ul li a').click(function() {
    $(this).parent().find('ul.sub-menu').toggle();
    return false;
});
like image 30
Kato Avatar answered Oct 18 '22 23:10

Kato


$('.sub-menu').hide();

$("a").click(function(){

    $(this).parent().children("ul").toggle();

})

check out this link http://jsfiddle.net/KhNCV/6/

like image 2
erimerturk Avatar answered Oct 19 '22 00:10

erimerturk