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:
JavaScript
x
6
1
const button = document.querySelector('button');
2
const box = document.querySelector('.box');
3
4
button.addEventListener('click', () => {
5
box.classList.toggle('hide');
6
})
JavaScript
1
15
15
1
.box {
2
width:200px;
3
height: 200px;
4
border: 1px solid #000;
5
background-color: gray;
6
margin: 0 auto;
7
opacity: 1;
8
display: block;
9
}
10
11
.hide {
12
display: none;
13
transition: all 1s ease-out;
14
opacity: 0;
15
}
JavaScript
1
2
1
<button>Show / Hide</button>
2
<div class="box hide"></div>
Advertisement
Answer
just remove the display: block
from your hide and if you want animated went div show add the animation too:
JavaScript
1
6
1
const button = document.querySelector('button');
2
const box = document.querySelector('.box');
3
4
button.addEventListener('click', () => {
5
box.classList.toggle('hide');
6
})
JavaScript
1
15
15
1
.box {
2
width:200px;
3
height: 200px;
4
border: 1px solid #000;
5
background-color: gray;
6
margin: 0 auto;
7
opacity: 1;
8
transition: all 1s ease-out;
9
display: block;
10
}
11
12
.hide {
13
transition: all 1s ease-out;
14
opacity: 0;
15
}
JavaScript
1
2
1
<button>Show / Hide</button>
2
<div class="box hide"></div>