JSFiddle - React, Tailwind, and code Playground

by Jakupov

HTML

<div id="transition" class="box box--transition"></div>
<div id="animation" class="box box--animation"></div>

CSS

.box {
  height: 100px;
  margin-bottom: 30px;
  width: 100px;
}

.box--transition {
  background-color: lightcoral;
  transition: width 0.5s ease-in-out;
}

.box--transition:hover {
  width: 300px;
}

.box--animation {
  background-color: lightblue;
}

.box--animation.box--hovered {
  animation: animateWidth2 0.5s ease-in-out;
  animation-fill-mode: forwards;
}

.box--animation:hover {
  animation: animateWidth 0.5s ease-in-out;
  animation-fill-mode: forwards;
}

.box--end {
  background-color: gray;
}

@keyframes animateWidth {
  from {
    width: 100px;
  }
  to {
    width: 300px;
  }
}
@keyframes animateWidth2 {
  from {
    width: 300px;
  }
  to {
    width: 100px;
  }
}

JavaScript

var boxTransition = document.getElementById("transition");
var boxAnimation = document.getElementById("animation");

/* add class after transition ends */
boxTransition.addEventListener("transitionend", changeBackground);

/* add class after keyframes animation ends */
boxAnimation.addEventListener("animationend", changeBackground);

function changeBackground() {
  this.classList.toggle("box--end");
  this.classList.add("box--hovered");
}