Skip to content

Instantly share code, notes, and snippets.

@bendc
Created June 22, 2016 03:01
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bendc/4958e1949eb75604a7ea7cf6e411716e to your computer and use it in GitHub Desktop.
Save bendc/4958e1949eb75604a7ea7cf6e411716e to your computer and use it in GitHub Desktop.
Transitioning the opacity of a hidden element
<!doctype html>
<meta charset="utf-8">
<title>Example</title>
<style>
div {
width: 100px;
height: 100px;
background: black;
animation-duration: .5s;
animation-fill-mode: forwards
}
.show { animation-name: show }
.hide { animation-name: hide }
@keyframes show { 0% { opacity: 0 } 100% { opacity: 1 } }
@keyframes hide { 0% { opacity: 1 } 100% { opacity: 0 } }
</style>
<button>toggle</button>
<div hidden></div>
<script>
{
let button = document.querySelector("button");
let div = button.nextElementSibling;
let open = false;
button.addEventListener("click", () => {
div.hidden = false;
div.className = open ? "hide" : "show";
open = !open;
});
div.addEventListener("animationend", () => {
if (!open) div.hidden = true;
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment