Conditional Toggle of Class using JQUERY
$('.showall').css("cursor","pointer").click(function() {
$('.value-container').toggle();
$('.dim-header').toggleClass($('.dim-header').toggleClass() == 'dim-header' ? 'dim-header active' : 'dim-header');
$('.sh开发者_JS百科owall').html($('.showall').html() == '+ Expand All' ? '- Hide All' : '+ Expand All');
return false;
});
I have a series of boxes that I let users expand and collapse at will. The JQUERY for that works great and the box gets a class of 'active' added to it upon expand and has that class removed upon collapse.
I have a link that fires off the code above that toggles all the boxes to expand or collapse and changes the header image to switch from + to -.
My problem is that if someone has a box or two expanded already before clicking the expand all or collapse all, the toggle won't force ALL the boxes to expand or collapse, the ones already expanded or collapsed do the opposite of the others. I think I need to check to see if the 'active' class is present and if so, either add expand to all or remove from all so the toggle does not get the boxes out of sync...
Can anyone help me with the logic to do this? I think I am close...
Thanks!
var showText = '+ Expand All';
var hideText = '- Hide All';
$('.showall').css("cursor","pointer").click(function(e) {
e.preventDefault();
var show = $('.showall').html() == showText;
$('.showall').html(show ? hideText : showText);
if (show) {
$('.value-container').show();
$('.dim-header').addClass("active");
}
else {
$('.value-container').hide();
$('.dim-header').removeClass("active");
}
});
Try this:
$('.showall').css("cursor","pointer").click(function(){
$('.value-container').toggle();
if($(this).html() == '+ Expand All'){
$('.dim-header').addClass('active');
$(this).html('- Hide All');
}
else{
$('.dim-header').removeClass('active');
$(this).html('+ Expand All');
}
return false;
});
精彩评论