Reputation: 135
how? when click the .button, hide all .body div tags and show just closest .body tag div
my codes first one works, but when click the .button, show .body, but when click again, does't toggle ( show / hide ) that, any more?
How to do it properly?
<div class="box">
<div class="header">
<a href="#" class="button">
<span class="positive"></span>
</a>
</div>
<div class="body">
</div>
</div>
.body {
display:none;
}
.button .positive,
.button .negative {
width:36px;
height:36px;
float:right;
display:block;
cursor:pointer;
}
.button .positive {
background:url('../img/icon-del.png') no-repeat center center / 18px;
}
.button .negative {
background:url('../img/icon-opn.png') no-repeat center center / 18px;
}
jQuery('.button').on('click' ,function(e) {
e.preventDefault(); // Is this necessary? for <a href="#"></a>
jQuery('.body').hide(); // Problem is hear i think
jQuery(this).closest('.box').find('.body').toggle();
});
Upvotes: 0
Views: 742
Reputation: 572
add class iconbtn
to button span
<div class="box">
<div class="header">
<a href="#" class="button">
<span class="iconbtn positive"></span>
</a>
</div>
<div class="body">
</div>
jQuery('.button').on('click' ,function(e) {
e.preventDefault();
var box = jQuery(this).closest('.box');
var closestBody = box.find('.body');
jQuery('.body').not(closestBody).hide(); // Hide all except above div
jQuery(closestBody).toggle(); // if visible hide it else show it
jQuery('.iconbtn').removeClass('negative').addClass('positive');
var iconBtn = box.find('.iconbtn');
if (jQuery(closestBody).is(':visible')) {
iconBtn.removeClass('positive').addClass('negative');
} else {
iconBtn.removeClass('negative').addClass('positive');
}
});
Upvotes: 2
Reputation: 421
The issue is that you have:
jQuery('.body').hide();
in your click
callback, that means the body
div is first being hidden and then toggle
works as it should - it shows the div
. There is no way it can hide it though, as before toggle
you always first hide the div
Remove this line and it should work, check it here: JS Fiddle
Upvotes: 2