Transition Animation

Animation using javascript and css3 transition

by Shishir Morshed

HTML

<div id="box"></div>
<button>play</button>

CSS

#box { width:100px; height:100px; background:#666; margin-left: 0px; margin-bottom:10px; }

JavaScript

var animate = function(elm,property,val,duration,cta){
    var _that = this;
    var _initialVal = window.getComputedStyle(elm).getPropertyValue(property);
    var _finalVal = val;
    var _state = 'initial';
    
    var _transition = property + ' ' + duration;
    this.play = function(){
        if(_state == 'initial' || _state == 'paused'){          
            elm.style.transition = _that.getTransition();
            elm.style[property] = _finalVal;
            cta.innerHTML = 'pause';
            _state = 'started';
        }else if(_state == 'started' || _state =='started-back'){
            elm.style[property] = window.getComputedStyle(elm).getPropertyValue(property);
            _state = (_state == 'started') ? 'paused' : 'paused-back';
            cta.innerHTML = 'resume';
        }else if (_state == 'finished' || _state == 'paused-back' ){
            elm.style.transition = _that.getTransition();
            elm.style[property] = _initialVal;
            cta.innerHTML = 'pause';
            _state = 'started-back';
        }
    };
    this.getTransition = function(){
        if(window.getComputedStyle(elm).getPropertyValue(property)== _initialVal || window.getComputedStyle(elm).getPropertyValue(property) == _finalVal){
            return property + ' ' + duration+'s';
        }else {
            var initialDiff = Math.abs(parseInt( _finalVal.trim().replace('px', ''))- parseInt(_initialVal.trim().replace('px', '')));
            var remaining = (_state == 'paused') ? Math.abs(parseInt( _finalVal.trim().replace('px', ''))-  parseInt(window.getComputedStyle(elm).getPropertyValue(property).trim().replace('px', ''))) : Math.abs(parseInt( _initialVal.trim().replace('px', ''))-  parseInt(window.getComputedStyle(elm).getPropertyValue(property).trim().replace('px', '')));
            var durationUpdate = ((remaining /(initialDiff/100))/100)*duration;

             return property + ' ' + durationUpdate +'s';
        }
    };

   var _transitionEndEvent =...