thenewseattle
thenewseattle

Reputation: 1451

why does it not work if I replace fadeIn/fadeOut with fadeToggle

I have two same jsfiddles , the latter replaced by fadeIn/fadeOut instead of fadeToggle.

Just move with your mouse in and out fast, and keep the last moment on the yellow box and wait, the red element won't fade in.

weird. anyone has an explanation for it?

http://jsfiddle.net/q6d57/5/ (working)

$(document).ready(function(){
      $(".box1").mouseenter(function(){
        $('.box2').stop(true, false).fadeToggle(1500);
      });
      $(".box1").mouseleave(function(){
        $('.box2').stop(true, false).fadeToggle(1500);
      });
    });

and

http://jsfiddle.net/q6d57/6/ (not working)

$(document).ready(function(){
  $(".box1").mouseenter(function(){
    $('.box2').stop(true, false).fadeIn(3000);
  });
  $(".box1").mouseleave(function(){
    $('.box2').stop(true, false).fadeOut(3000);
  });
});

Upvotes: 3

Views: 385

Answers (3)

Sico
Sico

Reputation: 1183

change jquery version to 2.0.2

Upvotes: 4

Alessandro Incarnati
Alessandro Incarnati

Reputation: 7248

The problem is that you are using fadeIn/Out with non hidden elements. That's why you need to add .hide() to make it work.

Check this fiddle:

http://jsfiddle.net/q6d57/10/

$(document).ready(function(){
  $(".box1").mouseenter(function(){
    $('.box2').stop(true, false).hide().fadeIn(3000);
  });
  $(".box1").mouseleave(function(){
    $('.box2').stop(true, false).hide().fadeOut(3000);
  });
});

Upvotes: 0

Cameron Askew
Cameron Askew

Reputation: 1413

At first I was a bit baffled but I'm gonna venture an educated guess at this one after playing around in the chrome debugger while watching fadeIn, fadeOut, & fadeToggle run it's course.

It seems as though what jQuery does with fadeIn is it checks the html element's display property. If the display is none, fadeIn fades the object in by setting the display to block and drifting the opacity from 0 to 1. So in your code, when you move your mouse away and back, it stops the fadeOut but since the display is still block, fadeIn fails to take affect.

However, fadeToggle is being a little smarter and checking opacity and not just the display property. Not only is it checking opacity, but probably keeps a flag on which fade was last executed (in or out) so it knows to do the other one.

This is all a bit of hearsay without digging into the jQuery library but I believe this is the only thing that could be happening after playing around in Chrome's awesome debugger ;).

Upvotes: 0

Related Questions