sdvnksv
sdvnksv

Reputation: 9668

How do I pause CSS transition?

I need to pause a CSS transition at any time during the transition. I know there is a solution with calculating the current value of the transitioning property and applying it directly, however this gave me "jumping" results in Safari and IE11.

What I though of is to increase the transition-duration value to something big, that is in my theory should have almost paused the transition, but it seems it's not the case:

https://jsfiddle.net/j8p0msff/

$('#pause').on('click', function() {
    $('.ball').css('transition-duration: 5000s');
});

Any other ideas? Thanks!

Upvotes: 3

Views: 14568

Answers (1)

Mazz
Mazz

Reputation: 1879

Transitions

A solution would be to remove the transition class and save the current state of styles (margin-leftin the example) when stopping. And when starting just add the transition class again.

var boxOne = document.getElementsByClassName('box')[0];
var running = false;

var toggleTransition = function() {
  if(!running) 
  { 
    boxOne.classList.add('horizTranslate');
  } else {
    var computedStyle = window.getComputedStyle(boxOne),
        marginLeft = computedStyle.getPropertyValue('margin-left');
    boxOne.style.marginLeft = marginLeft;
    boxOne.classList.remove('horizTranslate');    
  }  

  running = !running;
}
.box {
  margin: 30px;
  height: 50px;
  width: 50px;
  background-color: blue;
}
.box.horizTranslate {
  -webkit-transition: 3s;
  -moz-transition: 3s;
  -ms-transition: 3s;
  -o-transition: 3s;
  transition: 3s;
  margin-left: 50% !important;
}
<div class='box'></div> 
<button class='toggleButton' onclick='toggleTransition()'>Toggle</button>

Animations

You could use: animation-play-state

With e.g. Javascript: document.getElementById('myId').style.animationPlayState = 'paused'

var toggleAnimation = function(){
  state = document.getElementById('myId').style.animationPlayState == 'paused' ? 'running' : 'paused';
  document.getElementById('myId').style.animationPlayState = state;
}
div#myId {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: mymove 5s infinite; /* Safari 4.0 - 8.0 */
    -webkit-animation-play-state: running; /* Safari 4.0 - 8.0 */
    animation: mymove 5s infinite;
    animation-play-state: running;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}

@keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}
<div id='myId'></div>

<button onclick="toggleAnimation()">Toggle Animation</button>

Upvotes: 8

Related Questions