Sonntag, 27. August 2017

Playing and Pausing CSS Animations

I was recently asked how I would implement a slide show for a website. The requirements were that the slide show should start playing when hovering over it and pause while the mouse is elsewhere. GIF images are out of the question, because we can't control the playback. We could use javascript timers to control the animation and use the CSS transform: translate() property to pick the correct image from a spritesheet. Sounds like a total mess and also it would break if the user has disabled javascript. So maybe we could solve the whole thing using only CSS? I made a small codepen example demonstrationg how the slide show could be implemented. Instead of using images I'm using a colored div and change the background-animation as part of the animation. The container class contains the basic setup. The @keyframes block contains the information about what will happen during the animation. In this case the color will change from blue to purple to red. The animation class contains the setup for the animation. The animation has the name color, is initially paused and will last 4 seconds. When the user is hovering over the object with the animation class it will continue playing.