JSFiddle - React, Tailwind, and code Playground
Transition example with vanilla javascript and animate.css
by Travis Almand
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<div class="container"></div>
<button>toggle</button>
SCSS
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
html,
body {
padding: 0;
margin: 0;
}
body {
align-items: center;
display: flex;
flex-direction: column;
}
.container {
align-items: center;
background-color: #707070;
border: {
color: #333333;
style: solid;
width: 3px;
}
display: flex;
height: 200px;
justify-content: center;
margin: 20px;
overflow: hidden;
width: 300px;
}
.box {
border: {
color: #333333;
style: solid;
width: 2px;
}
height: 100px;
width: 100px;
}
.box1{
background-color: rebeccapurple;
}
.box2 {
background-color: #307B21;
}
JavaScript
console.clear();
let button = document.querySelector('button');
let container = document.querySelector('.container');
let box1 = document.createElement('div');
let box2 = document.createElement('div');
let removeClasses = function () {
box1.classList.remove('animated', 'fadeOutRight', 'fadeInLeft');
box2.classList.remove('animated', 'fadeOutRight', 'fadeInLeft');
}
let switchElements = function () {
let currentElement = document.querySelector('.container .box');
let leaveElement = currentElement.classList.contains('box1') ? box1 : box2;
let enterElement = leaveElement === box1 ? box2 : box1;
leaveElement.removeEventListener('animationend', switchElements);
leaveElement.remove();
enterElement.classList.add('animated', 'fadeInLeft');
container.append(enterElement);
}
box1.classList.add('box', 'box1');
box1.addEventListener('animationend', removeClasses);
box2.classList.add('box', 'box2');
box2.addEventListener('animationend', removeClasses);
container.appendChild(box1);
button.addEventListener('click', function () {
let currentElement = document.querySelector('.container .box');
if (currentElement.classList.contains('box1')) {
box1.classList.add('animated', 'fadeOutRight');
box1.addEventListener('animationend', switchElements);
} else {
box2.classList.add('animated', 'fadeOutRight');
box2.addEventListener('animationend', switchElements);
}
});