I am attempting to create a pause/play button ‘toggle’ for Lottie animation playback. The button appearance is provided by Font Awesome icons, defined in javascript to shaw a ‘play’ state when the animation is inactive, and a ‘pause’ state when the animation is active. The ‘play’ behavior appears to work as expected, however, ‘pause’ does not.
The issue does not elicit browser console errors, leading me to think that the EventListener is inadequately defined.
I have tried different methods to define the ‘pause’ javascript, but my code does not successfully stop the Lottie animation from playing.
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<title>Lottie Player Web Button Component</title>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.5.3/lottie_svg.min.js"></script>
<script src="https://kit.fontawesome.com/8a60cdf3a9.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://use.typekit.net/yil7vfv.css">
<style>
body {
font-family: Roboto;
background: #fff;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 40vh;
}
.fa-regular {
color: #666666;
font-size:30px;
}
.my-icon {
vertical-align: middle;
font-size: 24px;
}
.my-text {
font-family: "Courier-new";
}
.my-fancy-container {
border: none;
border-radius: 0;
display: inline-block;
margin: 60px;
padding: 10px;
}
#play-button {
padding-right: 16px;
}
</style>
</head>
<body>
<div id="lottie-animation" background="transparent" speed="0.5" style="width: 400px; height: 400px;"></div>
<div>
<a href="#" id="playPauseBtn"><i class="fa-regular fa-circle-play"></i></a>
</div>
<script>
// Initialize Lottie player
const animation = lottie.loadAnimation({
container: document.getElementById('lottie-animation'),
renderer: 'svg',
loop: true,
autoplay: false, // Set to false to initially not play
path: 'https://assets1.lottiefiles.com/datafiles/HN7OcWNnoqje6iXIiZdWzKxvLIbfeCGTmvXmEm1h/data.json' // Replace with your animation file
});
// Get buttons
const playPauseBtn = document.getElementById("playPauseBtn");
// Play button functionality
playPauseBtn.addEventListener("click", () => {
if (animation.pause) {
animation.play();
playPauseBtn.innerHTML = '<i class="fa-regular fa-circle-pause"></i>';
} else {
animation.pause();
playPauseBtn.innerHTML = '<i class="fa-regular fa-circle-play"></i>';
}
});
</script>
</body>
</html>