Reputation: 7959
Hey all, I've got some hidden divs that are shown via a dynamic slideToggle function. Everything works great, but the divs are left shown when you click on other links. I'd like one div shown at a time. Clicking hides the others and shows the new one. It seems I can never get the full function correct!
Thank you for your time! I appreciate it immensely. Just a 'lil baby here.
HTML:
<div id="nav">
<div class="menu"><a id="show_work">WORK</a></div>
<div id="work" class="sub">
<p>hidden content</p>
</div>
<div class="menu"><a id="show_biography">BIO</a></div>
<div id="biography" class="sub" >
<p>hidden content</p>
</div>
<div class="menu"><a id="show_contact">CONTACT</a></div>
<div id="contact" class="sub">
<p>hidden content</p>
</div>
</div>
Javascript that works but leaves them all open:
$('#work, #biography, #contact').hide();
$('#nav .menu').click(function() {
$(this).next().slideToggle(400);
return false;
}).next().hide();
Mangled conceptual Javascript of what I'd like:
$('#work, #biography, #contact').hide();
$('#nav .menu').click(function() {
$(this).slideToggle(400);
$('.sub not:(this)').slideUp(400);
});
return false;
});.next().hide();
Upvotes: 0
Views: 1738
Reputation: 2069
Is this what you're looking for?
$('.sub').hide();
$('#nav .menu').click(function() {
$('.sub:visible').not($(this).next()).slideUp(400);
$(this).next().slideToggle(400);
return false;
});
Here's a fiddle to watch it work.
Upvotes: 0
Reputation: 15413
The accordion control from jQuery UI seems like it would do what you're looking for.
Upvotes: 0
Reputation: 31761
I'd just write a function that hides all of the divs on any click:
function hideDivs() {
$(".menu div").hide();
}
Then your clicks look like this:
$('#show_work').click(function() {
hideDivs();
$('#work').slideToggle(400);
});
$('#show_biography').click(function() {
hideDivs();
$('#biography').slideToggle(400);
});
$('#show_contact').click(function() {
hideDivs();
$('#contact').slideToggle(400);
});
This works by hiding all of the divs no matter what link was clicked. You could hide the non-target divs manually (shown below), but I think hiding them all is a good approach.
Alternative, (uglier and less maintainable - also needs logic to skip the slideToggle call if the "show div" is already visible):
$('#show_work').click(function() {
$('#show_biography, #show_contact').hide();
$('#work').slideToggle(400);
});
$('#show_biography').click(function() {
$('#show_work, #show_contact').hide();
$('#biography').slideToggle(400);
});
$('#show_contact').click(function() {
$('#show_work, #show_biography').hide();
$('#contact').slideToggle(400);
});
Upvotes: 1