Mike McG Mike McG - 15 days ago 4
Javascript Question

Javascript Loop for show/hide DIVs

I have 6 DIVs that show and hide, triggered by an onClick event. Currently if you click the 6 different pictures that trigger these divs, they all show up on top of eachother.

I would like only one DIV to show up at a time. So when you click a different image, it hides the currently displayed div and shows the new one.

I am guessing I need to loop through these somehow, can anyone point me in the right direction? My code:

<script type="text/javascript">

$(document).ready(function () {

$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function () {
$(".slidingDiv").slideToggle();
});

$(".slidingDiv2").hide();
$(".show_hide2").show();
$('.show_hide2').click(function () {
$(".slidingDiv2").slideToggle();
});

$(".slidingDiv3").hide();
$(".show_hide3").show();
$('.show_hide3').click(function () {
$(".slidingDiv3").slideToggle();
});

$(".slidingDiv4").hide();
$(".show_hide4").show();
$('.show_hide4').click(function () {
$(".slidingDiv4").slideToggle();
});

$(".slidingDiv5").hide();
$(".show_hide5").show();
$('.show_hide5').click(function () {
$(".slidingDiv5").slideToggle();
});

$(".slidingDiv6").hide();
$(".show_hide6").show();
$('.show_hide6').click(function () {
$(".slidingDiv6").slideToggle();
});
});

</script>

Answer

Not completely sure if this is what you're going for, but something like this might work:

HTML:

<img class="div1" src=...>
<img class="div2" src=...>
<img class="div3" src=...>
<!-- more images can go here -->

<div class="div1">text1</div>
<div class="div2">text2</div>
<div class="div3">text3</div>
<!-- more divs to display go here -->

JQuery:

$("img").click(function () {
    $("div").slideUp(190);                      // hide divs previously shown
    var divSelect = $(this).attr('class');      // get class of div to show
    $("div."+divSelect).delay(200).slideDown(); // show div after other slides up
});

WORKING EXAMPLE