I am trying to show/hide some basic content divs. I believe the problem lies in using the .toggle function, which is not an issue with the function, but I'm just not sure if that's what I want/need. Currently, they work as I believe they are designed, show on click, hide on click. My problem is that I want the div to auto-hide if any of the other divs are clicked. The following code only works to show the corrosponding elements when clicked, and requires them to be clicked again to hide:
$('#open1').click(function() {
$('#content1').toggle();
});
$('#open2').click(function() {
$('#content2').toggle();
});
$('#open3').click(function() {
$('#content3').toggle();
});
$('#open4').click(function() {
$('#content4').toggle();
});
$('#open5').click(function() {
$('#content5').toggle();
});
The issue is this - when you click the element for #open1, #content1 is shown. YOU HAVE TO CLICK #open1 AGAIN TO HIDE IT. Otherwise, if you click the element for #open2 without previously clicking #open1 to hide, both #content1 and #content2 show up. I am pretty sure this is the nature of using .toggle ...
I tried some varying combos of using .fadeIn, .slideUp and .slideDown, and .slideToggle but just couldn't seem to get all the content divs to hide appropriately.
So my question is, how do I re-write the above code so that ONLY the corrosponding elements are shown at the same time, without the need to click again to hide the div? (In other words, when #open2 is clicked, all BUT #content2 is hidden.)
Thanks!
Try: Working Fiddle
HTML
<button type="button" id="open1" class="open"></button>
<button type="button" id="open2" class="open"></button>
<button type="button" id="open3" class="open"></button>
<button type="button" id="open4" class="open"></button>
<button type="button" id="open5" class="open"></button>
<div id="content1" class="content-div"></div>
<div id="content2" class="content-div"></div>
<div id="content3" class="content-div"></div>
<div id="content4" class="content-div"></div>
<div id="content5" class="content-div"></div>
JS
$('.open').click(function() {
var idNum = $(this).attr('id'); //open1 or open2 ...
// get corresponding content to toggle
idNum = idNum.replace('open', 'content');
// hide all visible content divs except current one
$('.content-div:visible:not(#' + idNum + ')').hide();
// show the current content div only
$(idNum).toggle();
});
This code simplifies so that you dont have to duplicate your code for extra buttons/divs that you might add in the future.
NOTE: I would further simplify this and instead of using id
I would use data-index=1
or 2, 3, 4 or 5.