I have a small jQuery snippet which animates an image caption, based on the image’s alt attribute if it exists.
It’s working fine but I have one small issue. I want a delay on the hover out (slideUp) animation, but only if the previous slideIn animation completed fully. In basic scenarios:
scenario 1: User hovers over image, caption fully animates in. User hovers out, animation delays (caption stays put) for 2 seconds, then animates out.
scenario 2: User hovers over image, caption begins to animate in, but user hovers out before it completed. Animation should immediately stop and animate out without delay.
Scenario 1 works perfectly. scenario 2 doesn’t. The delay happens on the partially animated elements before it slides out which isn’t desired. I can see the flaw in my code, but can’t seem to figure out how to address it.
Fiddle, and current script:
$('.pv-inner').hover(function() {
var img = $(this).find('img:first');
var text = img.attr('alt');
if (text !== undefined) {
//remove any existing captions
$(this).find('.kppImageCaption').remove();
//insert the new caption
img.after('<div class="kppImageText">' + text + '</div><div class="kppImageCaption"></div>');
//animate it in
$(this).find('.kppImageCaption').stop().slideDown('slow').animate({
opacity: 0.6
}, {
queue: false,
duration: 'slow',
complete: function() {
$(this).parent().find('.kppImageText').fadeTo(1000, 1);
}
});
}
}, function() {
//on hover out animate it out. Here is the problem. I only want the delay
//to occur if the above hover over animation completed - currently it delays
//in all cases.
$(this).find('.kppImageCaption, .kppImageText').stop().delay(2000).slideUp('slow', function() {
$(this).remove();
});
});
EDIT:
Final working fiddle. May help someone down the road.
Create variable, let’s call it
var animationStatus = falseJust before starting animating it it, set
animationStatus = truein
completefunction (see jQuery animate docs) setanimationStatus = falseIn your function which is responsible for hiding – create if statement. If animationStatus === false – delay. If animationStatus === true – without delay.
Good luck!