Pausing CSS3 Animations with JavaScript
(Please note, that since this is about CSS3 animations, this will only work on browsers that support CSS3. At the moment, the two best are Safari and Google Chrome.)
CSS3 animations are fun. They run well, look really nice, and can be hardware accelerated on devices. While they can’t yet accomplish things totally on par with Flash (yet), they are still very functional and worth looking into.
Now before I start, here’s the working version of the page we’re workin on in this article.
So let’s say you have a lovely CSS3 animation, like below:
0% { -webkit-transform: translateX(0px); }
100% { -webkit-transform: translateX(500px); }
}
.moveRightAnimation {
-webkit-animation-name: MoveRight;
-webkit-animation-direction: normal;
-webkit-animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
-webkit-animation-duration: 5s;
position:absolute;
}
The above CSS code will make whatever you give the class of .moveLeftAnimation move to the right, at a constant speed (linear), during a time of 5 seconds. This will repeat forever.
Now, let’s say you’re tired of that moving thing, and you want it to stop. Not only do you want it to stop, but you want to stop it on the fly. That’s where JavaScript comes in.
Let’s make this nifty JS function:
if(what != null && document.getElementById(what) != null) {
var elem = document.getElementById(what);
if(elem.style.webkitAnimationPlayState == 'paused')
elem.style.webkitAnimationPlayState = 'running';
else
elem.style.webkitAnimationPlayState = 'paused';
}
}
Beautiful!
There’s only two states to a CSS3 animation: running, and paused. Easy peasy, right?
For the simple way of integrating it in the page, we can put some inline JavaScript on a link to toggle the animation, like so:
And there you have it.
Now for the whole thing:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>I Love CSS</title>
<style type="text/css">
@-webkit-keyframes MoveRight {
0% { -webkit-transform: translateX(0px); }
100% { -webkit-transform: translateX(500px); }
}
.moveRightAnimation {
-webkit-animation-name: MoveRight;
-webkit-animation-direction: normal;
-webkit-animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
-webkit-animation-duration: 5s;
position:absolute;
}
</style>
<script type="text/javascript">
function toggleAnimation(what) { // 'what' is the ID of the element that has the animation class applied to it
if(what != null && document.getElementById(what) != null) {
var elem = document.getElementById(what);
if(elem.style.webkitAnimationPlayState == 'paused')
elem.style.webkitAnimationPlayState = 'running';
else
elem.style.webkitAnimationPlayState = 'paused';
}
}
</script>
</head>
<body>
<div id="iLikeToMoveIt" class="moveRightAnimation">I Like to Move It Move It...</div>
<p>
<a href="javascript:toggleAnimation('iLikeToMoveIt');">Toggle Animation</a>
</p>
</body>
</html>
Hot.
