Skip to content

Instantly share code, notes, and snippets.

@osvik
Created July 9, 2023 09:03
Show Gist options
  • Save osvik/d75d5bc83d45eee76258d02009cd1126 to your computer and use it in GitHub Desktop.
Save osvik/d75d5bc83d45eee76258d02009cd1126 to your computer and use it in GitHub Desktop.
Animate CSS JavaScript enter and leave example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animate CSS</title>
<!-- https://animate.style/ -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
</head>
<body>
<style>
#my-element {
background-color: rgb(65, 165, 165);
}
</style>
<div id="my-element" hidden="hidden" class="animate__faster">
<h1>An animated element</h1>
<p>To test enter and leave</p>
</div>
<div>
<button onclick="enter('#my-element', 'slideInLeft');">Enter</button>
<button onclick="leave('#my-element', 'slideOutLeft');">Leave</button>
</div>
<script>
const animateCSS = (element, animation, prefix = 'animate__') =>
new Promise((resolve, reject) => {
const animationName = `${prefix}${animation}`;
const node = document.querySelector(element);
node.classList.add(`${prefix}animated`, animationName);
function handleAnimationEnd(event) {
event.stopPropagation();
node.classList.remove(`${prefix}animated`, animationName);
resolve('Animation ended');
}
node.addEventListener('animationend', handleAnimationEnd, { once: true });
});
</script>
<script>
const enter = function (element, animation) {
const el = document.querySelector(element);
if (el.hasAttribute("hidden")) {
el.removeAttribute("hidden");
animateCSS(element, animation).then((message) => {
// Follow up
});
}
};
const leave = function (element, animation) {
const el = document.querySelector(element);
if (!el.hasAttribute("hidden")) {
animateCSS(element, animation).then((message) => {
// Follow up
el.setAttribute("hidden", "hidden");
});
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment