Reputation: 543
I am working on a site where I have 4 expandable divs using jquery's slide toggle. All works fine but I don't want more than 1 of those divs expanded at a time. In other words: when a div is expanded, other divs that are expanded should close. Accordion isn't an option I think because all the div's styling is different. Below is my code.
$(document).ready(function(){
// slidetoggles
$("#tgx-window").hide();
$("#tgx-button").show();
$("#tgs-window").hide();
$("#tgs-button").show();
$("#tgm-window").hide();
$("#tgm-button").show();
$("#tgl-window").hide();
$("#tgl-button").show();
$('#tgx-button').click(function(){
$('#tgx-button').toggleClass('closebutton');
$("#tgx-window").slideToggle();
});
$('#tgs-button').click(function(){
$('#tgs-button').toggleClass('closebutton');
$("#tgs-window").slideToggle();
});
$('#tgm-button').click(function(){
$('#tgm-button').toggleClass('closebutton');
$("#tgm-window").slideToggle();
});
$('#tgl-button').click(function(){
$('#tgl-button').toggleClass('closebutton');
$("#tgl-window").slideToggle();
});
HTML:
<a onclick="" class="show_hide" id="<?=strtolower($service['title']);?>-button"></a>
<div class="slidingDiv" id="<?=strtolower($service['title']);?>-window">
<?
$infoBox = '<h1>'.$service['subtitel'].'</h1>';
$infoBox .= $service['description'];
echo replaceTags($infoBox);
?>
</div>
Upvotes: 0
Views: 2259
Reputation: 8482
It's a bit hard to answer this question without knowing your HTML but here is a solution I hope;
HTML (I presume):
<div id="tgx-window">tgx window</div>
<div id="tgs-window">tgs window</div>
<div id="tgm-window">tgm window</div>
<div id="tgl-window">tgl window</div>
<button id="tgx-button">Show tgx</button>
<button id="tgs-button">Show tgs</button>
<button id="tgm-button">Show tgm</button>
<button id="tgl-button">Show tgl</button>
JavaScript:
jQuery(function($) {
var $windows = $('#tgx-window,#tgs-window,#tgm-window,#tgl-window'),
$buttons = $('#tgx-button,#tgs-button,#tgm-button,#tgl-button');
$windows.hide();
$buttons.on('click', function(e) {
var $id;
e.preventDefault();
$buttons.removeClass('closebutton');
$id = $('#' + this.id.split('-')[0] + '-window');// Get window id
$windows.slideUp();
if(! $id.is(':visible') ) {
$id.slideDown();
$(this).addClass('closebutton');
}
});
});
You can see a working example here.
Upvotes: 2
Reputation: 148120
Use class
instead of id
of button and probably its parent .tgx-window
$('.tgx-button').click(function(){
$(this).toggleClass('closebutton');
$(this).closest(".tgx-window").slideToggle();
});
Upvotes: 1