Skip to content Skip to sidebar Skip to footer

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 dire

Solution 1:

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;
}
<divclass='box'></div><buttonclass='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;}
}
<divid='myId'></div><buttononclick="toggleAnimation()">Toggle Animation</button>

Post a Comment for "How Do I Pause Css Transition?"