Reputation: 6355
I'm creating a navigation system using jQuery. What I want to achieve is having the parent elements visible on the page load and the child elements hidden. Which I have done very simply.
However when I toggle between the other parent elements I want to be able to hide the previous child elements so that I can only open up one <ul>
at a time.
//user nav
$('.child').hide();
$('.parent').click(function() {
$(this).find('ul').slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="rightBottom">
<h1 class="boxheadings">Other functions</h1>
<p class="boxp">Click this button to view your current published site in a new window. This will not show your most recent changes until you click the ‘Publish Changes’ button on the right, alternatively click view local to see unpublished changes.</p>
<ul id="usernav">
<li class="parent">Manage
<ul class="child">
<li>child11</li>
<li>child12</li>
</ul>
</li>
<li class="parent">Subscriptions
<ul class="child">
<li>E-Briefings</li>
<li>E-Briefings Subscriptions</li>
<li>Knowledge Briefings</li>
</ul>
</li>
<li class="parent">Media Store
<ul class="child">
<li>Image Store</li>
<li>Document Store</li>
<li>Media Store</li>
</ul>
</li>
</ul>
</div>
Upvotes: 3
Views: 11086
Reputation: 6967
done . it was very simple. I am hiding everything before showing the current ul.
see :
//hide all children initially
$('.child').hide();
//adding a click handlers to every all parents
$('.parent').click(function() {
//slide up the children which are open already
$('.child').slideUp();
//find the child of clicked parent and toggle its visibility
$(this).find('ul').slideToggle();
});
Upvotes: 4
Reputation: 28387
Just collapse all the UL
s before you expand any one:
Add this line before you do a slideToggle:
$('#usernav').find('ul').slideUp();
$('.child').hide();
$('.parent').click(function() {
$('#usernav').find('ul').slideUp();
$(this).find('ul').slideToggle();
});
Upvotes: 0
Reputation: 6648
Use this
$('.child').hide();
$('.parent').click(function() {
$(this).siblings('.parent').find('ul').slideUp();
$(this).find('ul').slideToggle();
});
Upvotes: 4