Hide, show div with jQuery

advertisements

I do FAQ page in my site. And have some problem with hide/show div blocks with answer to questions. I need to hide block if second time clicked on same link or other link. jsfiddle link with code here

 <div  class="question">
<a id="myHeader1" href="javascript:slideonlyone('newboxes1');" >First question?</a></div>
<div class="newboxes" id="newboxes1" style="display: block;" > </div>
 <div  class="question">
<a id="myHeader2" href="javascript:slideonlyone('newboxes2');" >Second question?</a>   </div>
<div class="newboxes" id="newboxes2" style="display: none;" > </div>

JS:

function slideonlyone(thechosenone) {
     $('.newboxes').each(function(index) {
          if ($(this).attr("id") == thechosenone) {
               $(this).slideDown(200);
          }
          else {
               $(this).slideUp(600);
          }
     });
}

How to close div block if user second clicked on same block? I tried with help markers, but it not work.


Try This,

function slideonlyone(thechosenone) {
    $('.newboxes').each(function (index) {
        $(this).slideUp(600);
        if ($(this).attr("id") == thechosenone && !$(this).is(':visible')) {
            $(this).slideDown(200);
        }
    });
}

Working Demo

Alternatively, you don't need to use loop try it like,

function slideonlyone(thechosenone) {
    $('.newboxes').slideUp(600);
    var $id=$('#'+thechosenone);
    if ( !$id.is(':visible')) {
        $id.slideDown(200);
    }
}

Live Demo