Sunday, 21 October 2018

Pause/resume CSS animations when switching tabs

I have a bunch of long-running CSS animations on a page. I want to pause them when a user switches to another tab and resume them when the user is back to the original tab again. For the sake of simplicity I don't aim for a cross-browser solution at this point; making it work in Chrome should be enough.

document.addEventListener('DOMContentLoaded', function(){ 
  var element = document.getElementById("test");
  document.addEventListener("visibilitychange", function() {
    if (document.hidden){
      element.style["animation-play-state"] = "paused";
    } else {
      element.style["animation-play-state"] = "running";
    }
  });  
});
div#test {
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  left: 50px;
  animation-name: move;
  animation-duration: 5s;
  animation-fill-mode: forwards;
  animation-timing-function: linear;
}

@keyframes move {
  to {
    left: 500px
  }
}
<div id="test"></div>

The code above moves a red rectangle horizontally from 50 to 500 px. It takes 5 seconds for the rectangle to complete the animation.

The problem: after the animation starts, switch to another browser tab; after some period of time (longer than 5 seconds) switch back to the first tab.

Expected result: the rectangle continues its path from the point where it left off.

Actual result: most of the times the rectangle appears in its final destination (500 px) and stops. Sometimes it works as expected though.

I played with different values for animation-fill-mode and animation-timing-function, but the result was always the same.

I also tried pausing/resuming the animation inside $(window).focus/ $(window).blur handlers with similar outcome.

All tests were performed in Chrome and Firefox, so it's not a browser-specific issue.

Vendor prefixes for CSS animation properties shouldn't be an issue, since the code works at least sometimes.

Is there a way to reliably pause/resume CSS animations when switching tabs?



from Pause/resume CSS animations when switching tabs

No comments:

Post a Comment