How to trigger or pause a CSS animation in Javascript
To trigger or pause a CSS animation in Javascript. You can use the animationPlayState property of the HTML DOM style to specify whether an animation is running or paused.
Syntax :
animation-play-state: running|paused|initial|inherit;
- running: This value is used to run / play an animation.
- paused: This value is used to pause an animation.
- initial: This value sets the animation-play-state property to the parent element value.
- inherit: This value is used to set the .animation-play-state property to default (running).
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Trigger or pause a CSS animation in Javascript</title>
<style>
/* Put the css code here. */
</style>
</head>
<body>
<div class="display-anim"></div>
<button type="button" id="play_stop">Trigger/Pause</button>
</body>
<script type="text/javascript">
// Put the javascript code here.
</script>
</html>
Javascript Code:
var anim = document.querySelectorAll('.display-anim');
document.getElementById('play_stop').onclick = function () {
for (var i = 0; i < anim.length; i++) {
if (anim[i].style.animationPlayState == 'paused') {
anim[i].style.animationPlayState = 'running';
}
else {
anim[i].style.animationPlayState = '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 |
|---|




