if($(var).css('display') == "block") with slideToggle?
I'm attempting to change an icon shown on the option title (.option-title
) when the content below e.g. (.add_to_rotation
) is toggled up or down. While down, the close (.retract-icon
) button should be shown, and while up the add (.expand-icon
) should be shown.
The problem I think lies in the delay from the time at which slideToggle
is called, until the property it's called on changes from display: hidden
to display: block
and vice versa.
Here's my code:
$('.option-title').click( function() {
var name = $(this).attr('id');
$('.' + name).slideToggle('slow');
if($('.' + name).css('display') == "block") {
$(this).html("Add to Rotation开发者_如何学Go? <div class=\"retract-icon\">");
} else {
$(this).html("Add to Rotation? <div class=\"expand-icon\">");
}
});
The first part of the if()
conditional executes fine, so the condition must be considered true, but when clicked again, the first condition is still considered true, and the contents of .option-title
doesn't change.
How could I have it work as per my description above?
Any help would be greatly appreciated ;).
I see two easy ways to solve this.
Instead of using slideToggle, detect the condition first, and then use either slideUp or slideDown, which will make your message appear while the slide is happening:
$('.option-title').click( function() {
var name = $(this).attr('id');
var slider = $('.' + name); // shortcut to the element that's being slid. There's probably a better variable name you can use but I don't know the context
if(slider.css('display') == "block") {
slider.slideUp('slow');
$(this).html("Add to Rotation? <div class=\"retract-icon\">");
} else {
slider.slideDown('slow');
$(this).html("Add to Rotation? <div class=\"expand-icon\">");
}
});
Or use a callback, which will mean your message won't appear until after the slide is done:
$('.option-title').click( function() {
var name = $(this).attr('id');
var slider = $('.' + name); // shortcut to the element that's being slid. There's probably a better variable name you can use but I don't know the context
slider.slideToggle('slow', function() {
if(slider.css('display') == "block") {
$(this).html("Add to Rotation? <div class=\"retract-icon\">");
} else {
$(this).html("Add to Rotation? <div class=\"expand-icon\">");
}
});
});
At least part of the problem could be that you are mixing classes
and ids
.
You retrieve an id
here
var name = $(this).attr('id');
but then search for a class
here
$('.' + name).slideToggle('slow');
Not sure that is what you are trying to do.
If not, change $('.' + name)
to $('#' + name)
精彩评论