JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Using JavaScript to add/remove "hide" class</h1>
<button class="element" onclick="hide()">Click to hide (and reappear in 2 secs)</button>
<h1>Pure CSS solution</h1>
<div class="element-css">Hover to hide me</div>
CSS
@keyframes show {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
}
100% {
display: block;
opacity: 1;
}
}
@keyframes hide {
0% {
display: block;
opacity: 1;
}
99% {
display: block;
}
100% {
display: none;
opacity: 0;
}
}
.element, .element-css {
animation: show 500ms linear;
animation-fill-mode: forwards;
cursor: pointer;
}
.hide, .element-css:hover {
animation: hide 500ms linear;
animation-fill-mode: forwards;
}
/*Irrelevant styling*/
body {
font-family: arial, helvetica, sans-serif;
}
.element {
padding: 20px;
}
.element-css {
padding: 20px;
background: #FF5235;
border-radius: 10px;
font-weight: bold;
color: #fff;
}
JavaScript
var el = document.querySelector('.element');
el.addEventListener('click', hide);
function hide() {
el.classList.add('hide');
setTimeout(function () {
el.classList.remove('hide');
}, 2000);
}