Reputation: 28318
I can't for the life of me figure out why this function I'm running isn't hiding the elements. When hovering over a list item I want two divs inside it to animate to a 49%
height and when the mouse leaves this list item they go back to 0
and get display: none;
again. However they just stay at display: block;
even though the statement in the callback function of the animate
executes.
Here's what it looks like when they're animated to 49%
:
And here's when they go back to 0
:
The two div
elements containing the images doesn't get hidden with the .hide()
function in the callback for some reason.
This is the function that doesn't work:
$('#site-wrapper').on('mouseenter', '#images-list li', function() {
$(this).children('div').show().stop().animate({height: '49%'}, 'fast');
}).on('mouseleave', '#images-list li', function() {
$(this).children('div').stop().animate({height: 0}, 'fast', function() {
$(this).children('div').hide();
});
});
This solution works but it hides it straight away without the user being able to see the animation, which I don't want:
$('#site-wrapper').on('mouseenter', '#images-list li', function() {
$(this).children('div').show().stop().animate({height: '49%'}, 'fast');
}).on('mouseleave', '#images-list li', function() {
$(this).children('div').stop().animate({height: 0}, 'fast').hide();
});
What should I do to solve this rather stupid bug?
Upvotes: 2
Views: 117
Reputation: 5958
From the docs on .animate()
(emphasis mine)
Complete Function
If supplied, the complete callback function is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but
this
is set to the DOM element being animated.
So instead of
...
.on('mouseleave', '#images-list li', function() {
$(this).children('div').stop().animate({height: 0}, 'fast', function() {
$(this).children('div').hide(); // Wrong line
});
});
It should be
...
.on('mouseleave', '#images-list li', function() {
$(this).children('div').stop().animate({height: 0}, 'fast', function() {
$(this).hide(); // Hide the same div that was animated
});
});
Upvotes: 2
Reputation: 167162
Can you please try this? It would be better to use a fiddle to demonstrate this:
$('#site-wrapper').on('mouseenter', '#images-list li', function() {
$this = $(this);
$this.children('div').show().stop().animate({height: '49%'}, 'fast');
}).on('mouseleave', '#images-list li', function() {
$this.children('div').stop().animate({height: 0}, 'fast', function() {
$this.children('div').hide();
});
});
Upvotes: 0