Triggering a CSS animation with Jquery
In this tutorial, we are going to see how to trigger a CSS animation with Jquery. You can use jQuery’s css() method in combination with CSS3’s animation-play-state property to play and stop CSS animations in the middle of a cycle.
HTML Code:
<!DOCTYPE html> <html> <head> <title>Triggering a CSS animation with Jquery</title> <style> /* Put the CSS Style Here */ </style> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> // Put the JQuery Style Here. </script> </head> <body> <div class="display-anim"></div> <button type="button" class="off">Stop the animation</button> <button type="button" class="on">Trigger the animation</button> </body> </html>[st_adsense]
JQuery Code:
$(document).ready(function() { $(".on").click(function() { $(".display-anim").css("animation-play-state", "running"); }); $(".off").click(function() { $(".display-anim").css("animation-play-state", "paused"); }); });
CSS Code:
.display-anim { height: 250px; margin: 12px 0; background: url("https://1.bp.blogspot.com/-SEBMg2X0IqM/XRyfgTMBBkI/AAAAAAAAFEE/_xBgKj-gxtY1MybpCBCmDIUL-_Jtjl6FQCLcBGAs/s320/car.png") no-repeat left center #57A6F6; -webkit-animation: test 4s infinite; animation: test 4s infinite; } @-webkit-keyframes test { 50% { background-position: right center; } } @keyframes test { 50% { background-position: right center; } }
Result |
---|