My goal is to create an animation when showing and hiding an HTML element. The show and hide is triggered by a button that toggles a class hide.
Here is my code:
const button = document.querySelector('button');
const box = document.querySelector('.box');
button.addEventListener('click', () => {
box.classList.toggle('hide');
})
.box {
width:200px;
height: 200px;
border: 1px solid #000;
background-color: gray;
margin: 0 auto;
opacity: 1;
display: block;
}
.hide {
display: none;
transition: all 1s ease-out;
opacity: 0;
}
<button>Show / Hide</button>
<div ></div>
CodePudding user response:
If you want to use animations do not use display:none
, you can use visibility
const button = document.querySelector('button');
const box = document.querySelector('.box');
button.addEventListener('click', () => {
box.classList.toggle('hide');
})
.box {
width:200px;
height: 200px;
border: 1px solid #000;
background-color: gray;
margin: 0 auto;
opacity: 1;
transition: all 1s ease-out;
visibility: visible;
}
.hide {
visibility: hidden;
transition: all 1s ease-out;
opacity: 0;
}
<button>Show / Hide</button>
<div ></div>
CodePudding user response:
just remove the display: block
from your hide and if you want animated went div show add the animation too:
const button = document.querySelector('button');
const box = document.querySelector('.box');
button.addEventListener('click', () => {
box.classList.toggle('hide');
})
.box {
width:200px;
height: 200px;
border: 1px solid #000;
background-color: gray;
margin: 0 auto;
opacity: 1;
transition: all 1s ease-out;
display: block;
}
.hide {
transition: all 1s ease-out;
opacity: 0;
}
<button>Show / Hide</button>
<div ></div>
CodePudding user response:
Removing display: none
and animating just the opacity is not a good approach as the box remains and takes space.
You can fade in and out from display: none
by listening to the animationend
event and toggling classes.
const button = document.querySelector('button');
const box = document.querySelector('.box');
button.addEventListener('click', () => {
const isVisible = box.getAttribute('data-visible') === 'true';
box.classList.remove('show', 'hide');
box.classList.toggle('showing', !isVisible);
box.classList.toggle('hiding', isVisible);
box.addEventListener('animationend', () => {
box.classList.remove('hiding', 'showing');
box.classList.toggle('hide', isVisible);
box.classList.toggle('show', !isVisible);
box.setAttribute('data-visible', !isVisible)
}, {
once: true,
})
})
.box {
width: 200px;
height: 200px;
border: 1px solid #000;
background-color: gray;
margin: 0 auto;
}
.show {
display: block;
}
.showing {
animation: showing 1s ease-out;
}
.hide {
display: none;
}
.hiding {
animation: hiding 1s ease-out;
}
@keyframes showing {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes hiding {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
<button>Show / Hide</button>
<div data-visible="false" ></div>