user7548189
user7548189

Reputation: 1016

Jquery fadeIn() with opacity:0 or visibility:hidden

Simple Question: I have a div that I want to fadein without using display:none on the div and css, because it gets rid of the div, instead of hiding it, making the elements below it move up.

When I use opacity:0 or visibility:hidden, fadein doesn't work.

Upvotes: 2

Views: 2242

Answers (2)

JCOC611
JCOC611

Reputation: 19709

In jQuery, if you just want to fade out without changes to display properties, you could use the following:

$element.animate({ opacity: 0 }, 1000);

For example:

$('#fade').click(function(){
    $('#fadeout').animate({ opacity: 0 }, 1000);
})
#fadeout{
     width: 100px;
     height: 100px;
     background: blue;
     color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="fade">Fade out now</button>
<br />
<div id="fadeout">I'm visible atm</div>
<div>some other stuff</div>

Upvotes: 1

Michael Coker
Michael Coker

Reputation: 53674

You can use $.fadeTo() to change opacity instead of display the same way you would with $.fadeIn().

You can also just toggle a class that changes opacity and use transition in CSS to handle the "fade" effect.

$('#fadeto').fadeTo(1000,1);
$('#css').addClass('visible');
#fadeto {
  opacity: 0;
}
#css {
  opacity: 0;
  transition: opacity 1s;
}
#css.visible {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>foo</div>
<div id="fadeto">fadeto</div>
<div>foo</div>
<div id="css">css</div>
<div>foo</div>

Upvotes: 4

Related Questions