How to run the CSS3 animation to the end if the selector is not matching anymore?

As discussed in comments there is currently no way to force an animation to complete one full cycle even after the selector rule which originally applied the animation is no longer applicable.

The only way to achieve this is by using scripting. Below is a sample snippet using JavaScript. What this does is to add a class (that has the animation property set) to the element when it gains focus and then remove it only when the animation ends.

Note:
I have used webkitAnimationEnd event in the snippet and so it would not work in other browsers. The code also needs more fine tuning because it currently removes the class only on animation end. So, if you tab out and tab in before one cycle is completed then nothing happens.

window.onload = function() {
  var anchors = document.querySelectorAll('a');
  for (var i = 0; i < anchors.length; i++) {
    anchors[i].addEventListener('focus', function() {
      addanim(this);
    });
    anchors[i].addEventListener('webkitAnimationEnd', function() {
      endanim(this);
    });
  }

  function addanim(el) {
    el.classList.add('focus');
  }

  function endanim(el) {
    el.classList.remove('focus');
  }
}
@keyframes pressed {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(2);
  }
}
.focus {
  animation: pressed 2s;
}
a,
input {
  border: 1px solid silver;
  padding: 5px;
  height: 40px;
  line-height: 28px;
  margin: 0px;
  display: inline-block;
  width: 33.3%;
  box-sizing: border-box;
  background: white;
}
a {
  color: dodgerBlue;
  text-decoration: none;
}
input {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

<input type="text" id="foo" value="Start here, then press tab" />
<a href="#">Lorem</a>
<a href="#">Ipsum</a>
<a href="#">dolor</a>
<a href="#">sit</a>
<a href="#">amet</a>
<a href="#">consectetur</a>
<a href="#">adipiscing</a>
<a href="#">elit</a>

The animationcancel event mentioned in comments (by BoltClock) could have been more useful for our case but it is just an event that is fired when an abnormal end to the animation is encountered. We would still have to write our own code to make it continue till the end of a cycle.

Leave a Comment