Search code examples
javascriptcsscss-animationsinternet-explorer-11

Removing class does not stop keyframe animation in IE11


The snippet below shows a simplified example of an issue I have found with css animations in Internet Explorer 11.

  1. The spin button adds the '.spin' class to the div, which should change the banner's colour and start it spinning.
  2. The stop button removes the '.spin' class from the div, which means it should revert to it's original colours and stop spinning.

In IE11 step 2 doesn't work - it changes the colours but does not stop the animation. Curiously if you try this with the developer tools running it works as expected.

Am I doing something wrong here or is this a known bug? I've been unable to find any reference to it although my google-fu might be lacking.

var banner = document.getElementById('banner');
var spinButton = document.getElementById("spin-button");
var stopButton = document.getElementById("stop-button");

spinButton.addEventListener("click", function(){
  banner.classList.add("spin");
})

stopButton.addEventListener("click", function(){
  banner.classList.remove("spin");
})
.spin {
  background: #FF0000;
  color: #FFF;
  -webkit-animation: spin 1.5s infinite linear;
  animation: spin 1.5s infinite linear;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
<div>
  <div id="banner">
    <p>
      Hello World
    </p>
  </div>
  <button id="spin-button">Spin</button>
  <button id="stop-button">Stop</button>
</div>


Solution

  • As pointed out by epascarello in the comments this is an IE11 bug, and the solution is to force the browser to redraw the affected element. In the example above simply updating the elements style.display property was enough to stop the animation:

    stopButton.addEventListener("click", function(){
       banner.classList.remove("spin");
       banner.style.display = "block";
    })
    

    In my real world problem I was using jQuery, so calling .show() on my element after removing the class was enough.