Reputation: 580
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.
Upvotes: 2
Views: 578
Reputation: 82251
You need to .slideToggle()
the content when id is matched(i.e. inside if condition) . However you can simply optimize the code to:
function slideonlyone(thechosenone) {
$('.newboxes').not('#'+thechosenone).slideUp(600);
$('.newboxes#'+thechosenone).slideToggle(200);
}
Upvotes: 2
Reputation: 40639
Try This,
function slideonlyone(thechosenone) {
$('.newboxes').each(function (index) {
$(this).slideUp(600);
if ($(this).attr("id") == thechosenone && !$(this).is(':visible')) {
$(this).slideDown(200);
}
});
}
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);
}
}
Upvotes: 2
Reputation: 189
you can try this..
function slideonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
if($(this).hasClass("open"))
{
$(this).slideUp(600);
$(this).removeClass("open");
}
else
{
$(this).slideDown(200);
$(this).addClass("open");
}
}
else {
$(this).slideUp(600);
}
});
}
Upvotes: 1
Reputation: 84
Set an active css class for opened element. So you can decide which element is openend and has to be closed on second click. Here the code:
function slideonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
if( $(this).hasClass( 'active' )) {
$(this).slideUp(600).removeClass( 'active' );
} else {
$(this).slideDown(200).addClass( 'active' );
}
}
else {
$(this).slideUp(600);
}
});
}
A demo you can find here: http://jsfiddle.net/p2622b1t/
Upvotes: 1
Reputation: 807
Please use slideToggle instead of slideDown. :)
http://jsfiddle.net/m9bdLw4c/1/
function slideonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideToggle(200);
}
else {
$(this).slideUp(600);
}
});
(Edit: Sorry, already been answered whilst I was editing. Didn't mean to duplicate!)
Upvotes: 1