Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fading an element in from display: none; with CSS transitions.
.box {
display: block;
background: red;
width: 200px;
height: 200px;
opacity: 1;
}
.box-hidden {
display: none;
}
/* ensure box is displayed block during the transition */
.box-transition.box-hidden {
display: block;
opacity: 0;
}
.box-transition {
transition: opacity 1s ease;
}
<div class="box">
</div>
<button class="button">Toggle Box</button>
document.addEventListener('DOMContentLoaded', function() {
var box = document.getElementsByClassName('box')[0],
button = document.getElementsByClassName('button')[0];
button.addEventListener('click', function(e) {
if (box.classList.contains('box-hidden')) {
// show
box.classList.add('box-transition');
box.clientWidth; // force layout to ensure the now display: block and opacity: 0 values are taken into account when the CSS transition starts.
box.classList.remove('box-hidden');
} else {
// hide
box.classList.add('box-transition');
box.classList.add('box-hidden');
}
}, false);
box.addEventListener('transitionend', function() {
box.classList.remove('box-transition');
}, false);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.