user342706
user342706

Reputation:

jQuery fadeOut without display none?

Is there an alternative to fadeOut() that doesn't use display:none for the style? I'd like to just use visibility hidden to avoid any sort of shifting in the page layout?

Upvotes: 82

Views: 51534

Answers (6)

jobima
jobima

Reputation: 5930

I you want to fadeOut, then change the content and then fadeIn again:

$("#layer").animate({opacity: 0}, 1000, 'linear', function(){

    //Do here any changes to the content (text, colors, etc.)
    $("#layer").css('background-color','red'); //For example

    $("#layer").animate({opacity: 1}); //FadeIn again

});

Upvotes: 2

Simon_Weaver
Simon_Weaver

Reputation: 145970

Note that

fadeTo(500, 0)   // fade out over half a second
fadeTo(0, 0)     // instantly hide

is (oddly) not compatible with

fadeIn()

(when you want to show it again). So if you are using

fadeTo(500, 0)

in order to to hide something without the css display: none then you must use

fadeTo(500, 1)

to fade it back in or it will still have opacity: 0 left over in the css and will remain invisible.

Upvotes: 0

friggle
friggle

Reputation: 3471

One way of doing this is to capture the display mode, then .fadeOut, and in the complete, do your preferred method of hiding, and set the display back to what it was:

var $element = $('#selector');

var display = $element.css('display');
$element.fadeOut(500, function() {
   $element.css('visibility', 'hidden'); 
   $element.css('display', display);
}

Upvotes: 2

user113716
user113716

Reputation: 322502

Yes, there's an alternative. It's called .fadeTo(), where you set the target opacity, which in your case will be 0.

$('element').fadeTo( 1000, 0 ); // fade to "0" with a 1000ms duration

This will not alter the display property at the end.

Upvotes: 75

please delete me
please delete me

Reputation:

Custom animation is an alternative http://api.jquery.com/animate/

.animate({opacity: 0.0}, 5000, 'linear', callback);

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630429

You can use .animate() on the opacity directly:

$(".selector").animate({ opacity: 0 })

This way the element still occupies space like you want, it just has a 0 opacity, so it's effectively the same as it being visibility: hidden when it finishes.

Upvotes: 124

Related Questions