Similar questions have been asked here in various forms of complexity. Some using jQuery:
How to toggle animate with css display:none.
And some very specific ones that over look the scope and simplicity of what is trying to be achieved:
JavaScript - add transition between display:none and display:block.
But take this very stripped down code for example:
var button = document.getElementsByTagName( 'button' )[ 0 ],
div = document.getElementsByTagName( 'div' )[ 0 ];
button.addEventListener( 'click', toggleVisibility );
function toggleVisibility(){
if(
div.classList.contains( 'show' )
){
div.classList.remove( 'show' );
div.classList.add( 'hide' );
}
else {
div.classList.add( 'show' );
div.classList.remove( 'hide' );
}
}
div {
height: 100px;
width: 100px;
background: #000;
transition: 1s;
}
.hide {
opacity: 0;
}
.show {
opacity: 1;
}
<p>A square</p>
<div class="show"></div>
<br>
<button>click to toggle hide/show</button>
This successfully toggles the opacity. But as soon as I add display: none
to the .hide
class the effect breaks horribly:
var button = document.getElementsByTagName( 'button' )[ 0 ],
div = document.getElementsByTagName( 'div' )[ 0 ];
button.addEventListener( 'click', toggleVisibility );
function toggleVisibility(){
if(
div.classList.contains( 'show' )
){
div.classList.remove( 'show' );
div.classList.add( 'hide' );
}
else {
div.classList.add( 'show' );
div.classList.remove( 'hide' );
}
}
div {
height: 100px;
width: 100px;
background: #000;
transition: 1s;
}
.hide {
display: none; /* added "display:none" in this example */
opacity: 0;
}
.show {
opacity: 1;
}
<p>A square</p>
<div class="show"></div>
<br>
<button>click to toggle hide/show</button>
What is a simple, reusable solution that we can use without any plugins or libraries to first fade out, then turn off display
and first turn on display
then fade in?
Edit: I am using display
over visibility
because in this example as in most cases I use this effect I want the element completly removed as it is usually on top of other elements hindering mouseover
/click
effects.