frenchie
frenchie

Reputation: 51937

jquery progressive fade in

I'm changing the value of a div when a user clicks on a control and I'm writing this:

$('#MyDiv').html(TheText);
$('#MyDiv').hide().fadeIn(1000);

The problem is that if the user clicks repeatedly on the control that triggers this code, MyDiv eventually disappears. I tried adding .stop() like this:

$('#MyDiv').stop().hide().fadeIn(1000);

but overall, the MyDiv still disappears.

What do I need to change?

Thanks.

Upvotes: 0

Views: 945

Answers (2)

ori
ori

Reputation: 7847

The problem is that fadeIn fades the element in by animating the element's opacity from 0 up to its previous opacity, so if you normally hide an element (default opacity 1), fadeIn will fade it in from 0 to 1.

However, if an animation was running before which brought the element to opacity 0.005 for example and you stop().hide().fadeIn(), then the element has opacity: 0.005 when entering the animation, and fadeIn will only bring its opacity from 0 up to 0.005, making it look invisible.

Instead you can do:

$('#MyDiv').stop().css({display: 'none', opacity: 1}).fadeIn(1000);

which not only hides the element but also resets its opacity back to 1, just before fading in.

See fiddle

Upvotes: 3

Wouter J
Wouter J

Reputation: 41934

It's a problem with the combination of fadeIn() and stop(). The solution is to use fadeTo() and set the opacity property of a value of 1.

Live example: http://jsfiddle.net/NhSh6/1/

Upvotes: 2

Related Questions