Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery opacity problems with fadein and fadeout

Tags:

jquery

http://dl.dropbox.com/u/921159/desktopography/index.html

I'm building a wallpaper blog and trying to use jquery to show/hide a download link (I'm a newbie). The problem is, if you hover over the image and let the link fade in, then quickly hover off and back on while it's fading out... the link will stop at the opacity it's currently at. It ends up being a problem when a user casually hovers over the images and the opacity gets stuck at 0. Whats causing this?

like image 529
dustinliamc Avatar asked Jan 20 '11 19:01

dustinliamc


3 Answers

clearQueue in the animation .stop() method defaults to false (see API) but you want it to be true because you want the current animation to clear and have it start the new hover state animation. Change your code as follows:

$(function() {
    $('.wallpaper').hover(function() {
        $(this).children('p').stop(true, true).fadeIn(300);   
    }, function() {
        $(this).children('p').stop(true, true).fadeOut(400);
    });
});
like image 177
mVChr Avatar answered Nov 15 '22 22:11

mVChr


This is a result of the fact that you're using stop()(docs) to halt the animation and reverse it. Trouble is that the next fade function remembers the stopped point, and uses that.

You can use fadeTo()(docs) instead so you can fix the opacity targets at 1 and 0.

$('.wallpaper').hover(function() {
    $(this).children('p').stop().fadeTo(300, 1);   
}, function() {
    $(this).children('p').stop().fadeTo(400 ,0);
});

EDIT: The equivalent using animate()(docs) is:

$('.wallpaper').hover(function() {
    $(this).children('p').stop().animate({opacity:1}, 300);   
}, function() {
    $(this).children('p').stop().animate({opacity:0}, 400);   
});

Note that neither of these will set display:none at the end. If you want that, you'll need to do it manually.

$('.wallpaper').hover(function() {
    $(this).children('p').show().stop().fadeTo(300, 1);   
}, function() {
    $(this).children('p').stop().fadeTo(400 ,0, function(){$(this).hide()});
})
  .children('p').css('opacity',0);
like image 34
user113716 Avatar answered Nov 15 '22 22:11

user113716


Take a look at the .stop() method. It's designed to fix these issues.

like image 45
Tom B Avatar answered Nov 15 '22 22:11

Tom B