Skip to content
Advertisement

Show and hide with CSS animation

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 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:

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 class="box hide"></div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement