Reputation: 19
I have this problem which is killing me ;(
I have the following HTML, all texto are hidden by css
<p><b><a class="titulo" href="#">Title</a></b></p>
<div class='texto'><p>Some text</p></div>
<p><b><a class="titulo" href="#">Title</a></b></p>
<div class='texto'><p>Some text</p></div>
<p><b><a class="titulo" href="#">Title</a></b></p>
<div class='texto'><p>Some text</p></div>
<div class='callToAtion bottomline'>
<a class="btnMeInteresa" href="#">Me interesa</a>
<a href="#">No, gracias</a>
</div>
I want the bottomline class to be shown ONLY when all texto are hidden. I have the following jquery, but doesn't work:
$(document).ready(function(){
$('.titulo').click(function(){
$($(this).closest('p').next()).slideToggle();
if ($('.texto:visible').length === 0){
$('.bottomline').show();
}
else {
$('.bottomline').hide();
}
return false;
})
});
Any ideas? Thanks in advance!
Upvotes: 1
Views: 68
Reputation: 1074238
slideToggle
is an animation, so you have to wait for it to end before you can determine whether any are visible:
$(document).ready(function(){
$('.titulo').click(function(){
$(this).closest('p').next().slideToggle(function() {
if ( $('.texto:visible').length === 0)
{
$('.bottomline').show();
}
else
{
$('.bottomline').hide();
}
});
return false;
});
});
Alternately, check ahead of time:
$(document).ready(function(){
$('.titulo').click(function(){
var texto = $(this).closest('p').next();
var targetCount = texto.is(":visible") ? 1 : 0;
var last = $('.texto:visible').length === targetCount;
texto.slideToggle();
if (last)
{
$('.bottomline').show();
}
else
{
$('.bottomline').hide();
}
return false;
});
});
Taking inspiration from JohnFx's comment on the question:
Example 1 updated:
$(document).ready(function(){
$('.titulo').click(function(){
$(this).closest('p').next().slideToggle(function() {
$('.bottomline').toggle(!$('.texto').is(':visible'));
});
return false;
});
});
Example 2 updated:
$(document).ready(function(){
$('.titulo').click(function(){
var texto = $(this).closest('p').next();
var targetCount = texto.is(":visible") ? 1 : 0;
var last = $('.texto:visible').length === targetCount;
texto.slideToggle();
$('.bottomline').toggle(last);
return false;
});
});
Upvotes: 3