Last active
December 30, 2023 00:37
-
-
Save richardscarrott/6457438 to your computer and use it in GitHub Desktop.
Fading an element in from display: none; with CSS transitions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="box"> | |
</div> | |
<button class="button">Toggle Box</button> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I finally managed to change the script so that the box is hidden at start and then displayed on click of the toggle button.
HTML
CSS
JavaScript
Not sure whether this is efficient way to do it but it works.