Reputation: 633
Can someone help me out with this code, i assume its easy if you know how..?
Currently click to toggle box appears below.
I need it so when you click on the other toggle, the box currently open closes, so its basically impossible for them to be both open at the same time?
But you can still toggle each individual one open/closed as normal, just when its open the other one (if open) closes also.
So far.. http://jsfiddle.net/CkTRa/380/
Thank you.
UPDATE:
Can it work with targeting independent boxes like so...?
HTML:
<div>
<h3 class = "trigger"> <a href="#box1">Heading 1</a></h3>
</div>
<div>
<h3 class = "trigger"><a href="#box2">Heading 2</a></h3>
</div>
<div class = "toggle" id="box1">
box one content
</div>
<div class = "toggle" id="box2">
box two content
</div>
jQuery so far:
$(".trigger").click(function(){
$(this).next(".toggle").slideToggle("slow");
});
Upvotes: 3
Views: 4951
Reputation: 482
I think this simple code should work perfectly
$(".trigger").click(function(){
$(".trigger").not(this).next(".toggle").slideUp("slow");
$(this).next(".toggle").slideToggle("slow");
});
Upvotes: 3
Reputation: 206121
A better approach would be:
jQuery:
$('.trigger').next('.toggle').hide();
$('.trigger').click(function() {
var el = $(this).next('.toggle');
var doit = el.is(':visible') ? el.slideUp() : ($('.toggle').slideUp()) (el.slideDown());
});
Upvotes: 0
Reputation: 500
Here is my solution to this problem:
$(".trigger").click(function() {
$(this).addClass('current');
$('.trigger:not(.current)').next(".toggle").slideUp('slow');
$(this).removeClass('current').next(".toggle").slideToggle("slow");
});
http://jsfiddle.net/paragnair/CkTRa/391/
UPDATE: The following example makes sure the heading you clicked slides only after other headings are slided up.
$(".trigger").click(function() {
var currentTrigger = $(this);
currentTrigger.addClass('current');
$('.trigger:not(.current)').next(".toggle").slideUp('slow', function(){
currentTrigger.removeClass('current').next(".toggle").slideToggle("slow");
});
});
http://jsfiddle.net/paragnair/CkTRa/392/
Upvotes: 0
Reputation: 60694
This is one solution: When you click one you first close all (if any), then open the one you clicked:
$(".trigger").click(function(){
$(".trigger").next(".toggle").slideUp("slow");
$(this).next(".toggle").slideDown("slow");
});
The only drawback is that if you click the open one again, you will close it and reopen it, but I'm not sure if that will be a problem with your functionality or not.
Upvotes: 0
Reputation: 136114
The easiest way is to add a class to the opened one, and use that class target the opened
one. For example, you could add a class open
when you open it, and use the selector .open
to close the opened one:
$(".trigger").click(function(){
$('.open').slideToggle('slow').toggleClass('open');
$(this).next(".toggle").toggleClass('open').slideToggle("slow");
});
Live example: http://jsfiddle.net/CkTRa/389/
Upvotes: 0