Reputation: 7253
I am using Jquery toggle method to display divs based on a link that the user will click.
http://jsfiddle.net/Rn9tg/905/
The only thing I want to change is to have the other menus close when a different one is clicked. So only 1 menu will ever be open at one time. Can someone show me the most straight forward method to achieve this?
Jquery
$(document).ready(function() {
$('#homeMenu').click(function() {
$('#menu1').slideToggle("fast");
});
$('#shopMenu').click(function() {
$('#menu2').slideToggle("fast");
});
$('#faqMenu').click(function() {
$('#menu3').slideToggle("fast");
});
});
HTML
<div id="Navigation">
<ul>
<li><a href="#" id="homeMenu">Home</a></li>
<li><a href="#" id="shopMenu">Shop</a></li>
<li><a href="#" id="faqMenu">FAQ</a></li>
</ul>
</div>
<div id="menu1" style="display:none;">This is menu one</div>
<div id="menu2" style="display:none;">This is menu two</div>
<div id="menu3" style="display:none;">This is menu three</div>
Upvotes: 0
Views: 60
Reputation: 61079
It's rarely a good idea to use a bunch of IDs for this type of thing. Instead, use DOM traversal relative to the clicked element:
$('#navigation ul li').click(function () {
var idx = $(this).index();
$('#content > div').eq(idx).slideToggle().siblings().slideUp();
});
Note that I did put a wrapper around the content. This solution depends on just two IDs, and that could be reduced to one with some additional markup changes.
Upvotes: 2
Reputation: 2599
You can slideUp manually the other containers.
var menus = ['#menu1', '#menu2', '#menu3']
$('#homeMenu').click(function() {
$('#menu1').slideToggle("fast");
$(menus.join(',').replace('#menu1')).slideUp();
});
$('#shopMenu').click(function() {
$('#menu2').slideToggle("fast");
$(menus.join(',').replace('#menu2')).slideUp();
});
$('#faqMenu').click(function() {
$('#menu3').slideToggle("fast");
$(menus.join(',').replace('#menu3')).slideUp();
});
http://jsfiddle.net/Rn9tg/906/
Upvotes: -1
Reputation: 162
Probably to place your divs in a container:
<div>
<div id="menu1" style="display:none;">This is menu one</div>
<div id="menu2" style="display:none;">This is menu two</div>
<div id="menu3" style="display:none;">This is menu three</div>
</div>
And then alter your JavaScript for each menu item like so:
$('#menu1').slideToggle("fast").siblings().hide();
Upvotes: 1