Mike McG Mike McG - 9 months ago 66
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 () {

$('.show_hide').click(function () {

$('.show_hide2').click(function () {

$('.show_hide3').click(function () {

$('.show_hide4').click(function () {

$('.show_hide5').click(function () {

$('.show_hide6').click(function () {


Answer Source

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


<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 -->


$("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