In this blog,
We are going how to create play and stop CSS animation using jQuery.
Step-1: include the jQuery link in the <head>..</head>tag on index.html file.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Step-2: Create Html Code in the index.html file.
<body> <div class="animate-box"> </div> <div class="buttons"> <button type="button" class="play-animation">Play Animation</button> <button type="button" class="stop-animation">Stop Animation</button> </div> </body>
Step-3: Add CSS Code in the <style>…</style> on index.html file.
<style> body{ margin: 0; } .animate-box { height: 80vh; margin: 10px 0; background: url("fish-image.png") no-repeat left center #000; -webkit-animation: test 4s infinite; /* Chrome, Safari, Opera */ animation: test 4s infinite; background-size: contain; } @-webkit-keyframes test { 50% {background-position: right center;} } /* Standard syntax */ @keyframes test { 50% {background-position: right center;} } .buttons{ text-align: center; } .buttons button{ background: #000; color: #fff; padding: 10px; border-radius: 12px; } </style>
Step-4: Now I added code in my <script>…</script> tag on index.html file.
<script> $(document).ready(function(){ $(".play-animation").click(function(){ $(".animate-box").css("animation-play-state", "running"); }); $(".stop-animation").click(function(){ $(".animate-box").css("animation-play-state", "paused"); }); }); </script>