Why does jQuery fadein not work if the element has zero opacity?

Asked

Viewed 629 times

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 an effect of fade-in in the element. I tried the following:

$('div').fadeIn();

Demonstration in jsfiddle

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

2 answers

9

The jQuery does not fade to opacity, example

I found a resposta interessante (in English) that talks about it. And interestingly the jQuery consider opacity:0 as not hidden!

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

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

  • use .Animate() as you mentioned
  • or using the .fade() which is thought for opacity, by example: $('div').fadeTo(2000, 1);

This was apparently discussed in the past but in the end it was not changed.

  • 1

    Thank you Sergio. See my comment in the mgibsonbr reply, there I explain what confused me.

  • 1

    @bfavaretto, I also came across this problem a while ago and interestingly because the .fade('in') Mootools has the problem reversed. Fade to opacity and not to display.

8


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

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

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

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

Example. Note that although the element is not initially invisible (i.e. without the display: none), the transition of opacity is normally carried out.

  • I get it. The catch is that the fade effect is only possible through the animation of opacity. It led me to think that the role of the fadeIn would animate the opacity up to 1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.