Reputation: 1674
I am trying to make a hover effect for my sidebar. But for some reason the the elements I have inside the sidebar doesn't fade in if I hover on it too much. You can see the working beta version here:
$('#sidebar').stop().animate({ 'width': '40px'}, 500);
$('#sidebar .icon').stop().fadeIn(0);
$('#sidebar #logo').stop().fadeOut(0);
$('#sidebar #nav').stop().fadeOut(0);
$('#sidebar .quote').stop().fadeOut(0);
$('#sidebar .branding').stop().fadeOut(0);
// sidebar
$('#sidebar').hover(function(){
$('#sidebar').stop().animate({ 'width': '200px'}, 500);
$('#sidebar .icon').stop().fadeOut();
$('#sidebar #logo').stop().fadeIn();
$('#sidebar #nav').stop().fadeIn();
$('#sidebar .quote').stop().fadeIn();
$('#sidebar .branding').stop().fadeIn();
}, function(){
$('#sidebar').stop().animate({ 'width': '40px'}, 500);
$('#sidebar .icon').stop().fadeIn(function(){ $(this).removeClass('flipped');});
$('#sidebar #logo').stop().fadeOut();
$('#sidebar #nav').stop().fadeOut();
$('#sidebar .quote').stop().fadeOut();
$('#sidebar .branding').stop().fadeOut();
});
Upvotes: 0
Views: 139
Reputation: 33880
To fade in, the element must be considered as :hidden
. So if you hover while it is fading out, jQuery will not fadeIn since the element is visible.
There is 2 solutions. The first one is to use .stop(true, true)
. Using true as argument mean "clear queue and jump to end" and the element will be hidden before the fadeIn()
.
But the solution i like the most is to use fadeTo()
:
$(el).fadeTo('slow', 0); //Hide element
$(el).fadeTo('slow', 1); //Show element
Here an more readable code for you :
var $sidebar = $('#sidebar'),
$icons = $sidebar.find('.icon'),
$otherObj = $sidebar.find('#logo, #nav, .quote, .branding')
$('#sidebar').hover(function(){
$sidebar.stop().animate({ 'width': '200px'}, 500)
$icons.stop().fadeOut()
$otherObj.stop().fadeIn();
}, function(){
$sidebar.stop().animate({ 'width': '40px'}, 500)
$icons.stop().fadeIn().done(function(){ $(this).removeClass('flipped');})
$otherObj.stop().fadeOut();
});
Upvotes: 3