Why does jQuery fadeIn not work if element has zero opacity?

12

I have an element with zero opacity defined via JavaScript. In practice, this is equivalent to:

<div style="opacity: 0"></div>

My intention is to use jQuery to make a fade-in effect on the element. I've tried the following:

$('div').fadeIn();

Demonstration in jsfiddle

However, the element continues with zero opacity, and is never visible. I know I can work around the problem using animate or display: none , but why fadeIn does not work?

    
asked by anonymous 17.01.2014 / 20:10

2 answers

8

The goal of fadeIn is not to "animate the opacity of the element", but rather to transition from invisible to visible. By "invisible" I mean display: none . The animation of the opacity is only a trick for the element to depart from the opacity 0 (in fact invisible) to its current opacity (whatever it is).

As this example in jsFiddle shows, an element initially hidden will become "visible" (ie take up space in the screen) when you use fadeIn . But its final opacity will be that which it actually has (that is, 0 ). ( another example , showing that the transition actually occurs but does not go to 1 )

If you want a method that allows you to choose a final opacity - regardless of that element's - try fadeTo .

$("div").fadeTo(2000, 1); // tempo, opacidade final, callback

Example . Note that even though the element is not initially invisible (i.e. without the display: none ), the opacity transition is performed normally.

    
17.01.2014 / 20:24
9

jQuery does not fade to opacity , example

I found a resposta interessante (in English) that talks about this. And curiously jQuery considers opacity:0 as not hidden!

<div style="opacity: 0"></div>
console.log($('div').is(':hidden')); //false

The fade applies to the display property. To make a fade to opacity, then the solution is:

This was seen discussed in the past but was not changed.

    
17.01.2014 / 20:27