Nazmul Nazmul - 5 months ago 11
Javascript Question

Hide and show parents and child menubar

I am trying to making a menubar. When someone clicks on parent li ( showul) i want to slidedown child li (hideul). and again when someone clicks on another parent li, it should open the respective child li as well as hide all the previously opened li. check my jsfiddle for better understanding. Kindly help. I am learning jQUery.

<ul>
<li><a href="#" id="update" class="showul">Update Pages</a>
<ul class="hideul">
<li>About Us</li>
<li>Contact Us</li>
</ul>
</li>
<li><a href="#" id="category" class="showul">Category Option</a>
<ul class="hideul">
<li>Add Category</li>
<li>Category List</li>
</ul>
</li>
<li><a href="#" id="postoption" class="showul">Post Option</a>
<ul class="hideul">
<li>Add Post</li>
<li>Post List</li>
</ul>
</li>
</ul>


$(document).ready( function() {
$(".showul").click(function(){
$(".hideul").slideToggle("slow");
});
});

Answer

Firstly you need to use siblings() to find the ul related to the current a. Then to hide all the other ul while toggling the current one, you can use this:

$(".showul").click(function() {
    var $hideUl = $(this).siblings(".hideul");
    var show = !$hideUl.is(':visible');
    $('.hideul').slideUp('slow');
    if (show)
        $hideUl.slideToggle('slow');
});

Update fiddle

Comments