Ending an infinite animation loop smoothly with javascript and css

Jun 1, 2017 javascript css animation infinite loop
If you want end an animation smoothly here’s how.

I wanted to end an infinite looping animation that gradually fades from 1 to 0 opacity over a period of time. Most solutions would end immediately mid frame before the animation loop has completed.

There are three event listeners that can be attached to an element, those three are “animationstart”, “animationiteration” and “animationend”. 0 opacity would seem the best time to end the loop. The events are fired as they say they do, use animationstart to fire at the beginning and animationend to fire once the the animation has finished, that is not at the end of the loop but at the end of a finite iteration. Animationiteration fires at the end of each iteration.

Here’s our element providing an endless loop

<div class=“myScroller myAnimation”></div>

So let’s grab the targeted element in javascript

el = document.querySelector(“.myScroller”);

I’d like the animation to end on a scroll.

window.onscroll = function () {
el.addEventListener('webkitAnimationIteration', endAnimation); //support for webkit browsers
el.addEventListener('animationiteration', endAnimation);

At this point what I noticed that removing the “myAnimation” class wasn’t enough.

function endAnimation() {

The loop would end, but the animation returns to it’s first frame. Since there are multiple methods to control the visibility of a class via css, we can use display or visibility properties. But remember visibility, display and opacity all affect the element in different manners. Let’s say we want to hide the element with each property individually.

Opacity still responds to events (mouse click) and the tab order (like a form) and it doesn’t affect the layout of other elements around it.

Visibility, is the same in regards to the layout but the difference here is it won’t responds to events and tabbing.

Display will act as if the element didn’t exist, it will collapse adjacent elements and won’t respond to events and tabbing.

I opted to use display, since my element had a position:absolute, I didn’t need to deal with other elements being affected.

function endAnimation() {
el.style.display = “none”;

Now when our element has an opacity of 0, we’ll hide the element. Remove the animation. The element would have returned to it’s first frame but we won’t see it.

If you found the following info helpful, I'm happy to accept any donations of the following cryptocurrencies.

  • Bitcoin - 17DTiPExzP9StqveW428acEyB4mVMfKbiK
  • Ethereum - 0x87B8307FD20dc90cc05c94905Ec593134D32B6FF
  • Litecoin - LZMiz5U5sVq9doMLYE3gfLJrxCQDKuyCmU
  • Neo - AXv71WB38ajc1KUUEnxQKhynLLPc4BapVb