2

Coming from https://stackoverflow.com/a/9334132/3779853: Let's assume a basic element that gets toggled programmatically. This could mean setting display to none/block or removing/inserting the element altogether.

$('#toggle').click(() => $('#square').toggle());
#square {
  width: 50px;
  height: 50px;
  background: lightblue;
}
.animated {
  animation: fade-in 1s;
}
@keyframes fade-in {
    from { opacity: 0; }
      to { opacity: 1; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="toggle">toggle</button>
<div id="square" class="animated"></div>

With a simple animation, you can add a transition effect for when the element appears. How do you do the same thing for when the element disappears?

I do not want to add further classes, no :hover, and no more Javascript code. In many JS frameworks, you can show/hide elements easily: .toggle() (JQuery, as above), ng-if (AngularJS), *ngIf (Angular), conditional rendering (React), v-if (VueJS) and so on. With above solution, a simple class="animated" is enough to have it appear with custom animations. So I am looking for a pure CSS solution for fade out animation here, assuming this is a standard problem.

phil294
  • 10,038
  • 8
  • 65
  • 98
  • 1
    You can't do this without "more JavaScript code" or "adding further classes". `toggle()` simply applies `display: none;`, and `display` is not an animatable/transitionable property. – Tyler Roper Aug 20 '18 at 03:24

2 Answers2

5

You can use the opacity property with transition effect.

$('#toggle').click(() => $('#square').toggleClass('animated'));
#square {
  width: 50px;
  height: 50px;
  background: lightblue;
  transition: opacity 0.5s;
  opacity: 1;
}
#square.animated {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="toggle">toggle</button>
<div id="square" class="animated"></div>
Bikas
  • 856
  • 7
  • 16
5

Here is a 100% pure css solution.

#square {
 width: 50px;
 height: 50px;
 background: lightblue;
 transition: opacity 1s ease-in-out;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition:opacity 1s ease-in-out;
}
#myBox:checked ~ .animated {
  opacity: 0;
}
#myBox ~ .animated {
   opacity: 1;
}
<input type="checkbox" id="myBox" style="display:none;"/>
<button id="toggle"><label for="myBox">toggle</label></button>
<div id="square" class="animated"></div>
Robbie
  • 700
  • 2
  • 6
  • 18