Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@towkir
Created October 27, 2018 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save towkir/e193cb76a00edb8717662f5552f7e2cf to your computer and use it in GitHub Desktop.
Save towkir/e193cb76a00edb8717662f5552f7e2cf to your computer and use it in GitHub Desktop.
<!-- This is a solution for a question on stackoverflow -->
<!-- https://stackoverflow.com/questions/52892889/pause-resume-css-animations-when-switching-tabs -->
<!DOCTYPE html>
<html>
<head>
<title>animation</title>
<style type="text/css">
div#test {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
left: 10vw;
animation-name: move;
animation-duration: 5s;
animation-fill-mode: forwards;
animation-timing-function: linear;
/* add the state here and set it to running on window load */
-webkit-animation-play-state: paused;
animation-play-state: paused;
}
@keyframes move {
to {
left: 90vw
}
}
</style>
</head>
<body>
<div id="test"></div>
<script type="text/javascript">
window.onload = function() {
// not mentioning the state at all does not provide the expected result, so you need to set
// the state to paused and set it to running on window load
document.getElementById('test').style.WebkitAnimationPlayState = "running";
document.getElementById('test').style.animationPlayState = 'running';
}
window.onblur = function(){
document.title = 'paused now';
document.getElementById('test').style.WebkitAnimationPlayState = "paused";
document.getElementById('test').style.animationPlayState = 'paused';
document.getElementById('test').style.background = 'pink'; // for testing
}
window.onfocus = function(){
document.title = 'running now';
document.getElementById('test').style.WebkitAnimationPlayState = "running";
document.getElementById('test').style.animationPlayState = 'running';
document.getElementById('test').style.background = 'red'; // for testing
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment