2

I am using the following code to acheive a fadeIn/fadeOut effect on rollover/rollout of it's parent div.

$('.rollover-section').hover(function(){  
   $('.target', this).stop().fadeIn(250)
 }, function() {
   $('.target', this).stop().fadeOut(250)
})

It works correctly when I rollover the div and out slowly. However if I move my mouse over and then off the div quickly, it breaks the effect. The target div seems to get stuck at an opacity between 0 and 1.

What confuses me is that when I use the following code it works perfectly.

$('.rollover-section').hover(function(){  
  $('.target', this).stop().animate({
      opacity: 1
    }, 250);
}, function() {
  $('.target', this).stop().animate({
      opacity:0 
    }, 250);
})

So, I have two questions.

1 - why is my first code block behaving as it does?

2 - What is the difference between fadeIn()/fadeOut() and animating the opacity?

Blowsie
  • 40,239
  • 15
  • 88
  • 108
Finnnn
  • 3,530
  • 6
  • 46
  • 69
  • 2
    Just use the animate example you have there. Check here for an answer to why: http://stackoverflow.com/questions/5967313/jquery-fade-flickers – Luwe Aug 24 '11 at 08:33
  • Cool thanks. The display:none is a bit of a nuisance. I presume the fade functions were never intended to be used I want them to be. – Finnnn Aug 24 '11 at 08:36
  • Interesting. I don't know enough about jQuery to know what's going on, but I can definitely reproduce the issue ([jsFiddle here](http://jsfiddle.net/gothick/TFhzE/).) – Matt Gibson Aug 24 '11 at 08:36
  • @Luwe post your comment as the answer to be accepted. – Tim B James Aug 24 '11 at 11:03
  • 1
    @Matt Gibson although you could use fadeTo instead. http://jsfiddle.net/TFhzE/1/ i believe that will resolve it. – Matt Aug 24 '11 at 11:04
  • @Tim B James: At first I didn't post it as an answer because I thought it would be closed due to duplication. – Luwe Aug 24 '11 at 11:17

2 Answers2

1

As it was stated already it's because those modify the css and change the display to none. By using fadeTo you can get the same effect, but it doesn't modify the css, so it should work correctly.

update example: http://jsfiddle.net/TFhzE/1/

you can also do

$('.rollover-section').hover(function() {  
   $('.target', this).stop().fadeTo(0,250);
 }, function() {
   $('.target', this).stop().fadeTo(250,0,function(){$(this).hide();});
});

to completely hide it yourself once it actually is complete.

Matt
  • 7,049
  • 7
  • 50
  • 77
0

I've put my answer from the comments here:

Just use the animate example you have there. Check here for an answer to why the fade animation behaves the way it does: jQuery fade flickers

Community
  • 1
  • 1
Luwe
  • 3,026
  • 1
  • 20
  • 21