June 19, 2010

In jQuery, can you fadeOut() without losing the element's real estate? (invisible vs display: none)

Question by 動靜能量

Because I need to fadeIn() another element of the same size back in, is there a way to fadeOut() the element so that the space is kept, so that the other elements are not re-flowed for a split second and then the fadeIn() will bring back another element with the same size?

Answer by ckramer

Two techniques come to mind:

  1. Wrap the element in a div which occupies the correct amount of space.
  2. Use the .animate method to change the opacity of the item from 100% to 0%, then, when the animation completes, swap the new element in and once again use animate to change the opacity from 0% to 100%.

Answer by Starx

Keep the element you want to fade inside a fixed <div style="display:block;width:300px;height:200px;">, then if you hide the element inside it, it will not affect the layout at all.

In jQuery, is prepend().hide().fadeIn() not so smooth?

Question by 動靜能量

in jQuery, will the following be not so smooth?

$('<a href= ... ><img src= ...  /></a>').prependTo($('#someDiv')).hide().fadeIn()

Will it actually shows the added element for a split second, and then hide it, and then fadeIn ?

Then will the animation be not so smooth?

Is there any better method?

Or the following?

$('<a style="display:none" href= ... ><img src= ...  /></a>').prependTo($('#someDiv')).fadeIn()

or

$('<a href= ... ><img src= ...  /></a>').hide().prependTo($('#someDiv')).fadeIn()

Update: the original was

$('#someDiv').prepend('<a href= ><img src  /></a>').hide().fadeIn()

which actually may be hiding the #someDiv and then fading it in?

Answer by Nick Craver

You can rearrange it a bit using .prependTo(), like this:

$('<a href= ... ><img src= ...  /></a>').hide().prependTo('#someDiv').fadeIn();

This allows you to call .hide() before adding it, so no visual artifacts.

Answer by Starx

How about fading it first and then prepending it and only showing it then, quite smooth right?

$('#someDiv').fadeOut("fast").prepend('<a style="display:none" href= ><img src  /></a>').fadeIn("slow");
...

Please fill the form - I will response as fast as I can!