Created
September 15, 2012 06:06
-
-
Save amsul/3726529 to your computer and use it in GitHub Desktop.
Basic JS animation method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Taken from: http://codepen.io/hakimel/pen/hGwmg | |
* | |
* Animates the given set of properties on the specified | |
* element. Properties should include units where possible, | |
* px will not be added automatically. For example: | |
* | |
* animate( document.querySelector( 'body' ), { | |
* width: '200px' | |
* }, { | |
* duration: 400, | |
* complete: function() { } | |
* } ); | |
*/ | |
function animate( element, properties, config ) { | |
var interpolations = {}, | |
startTime = new Date().getTime(); | |
// Find the start value and unit of each properties | |
for( var p in properties ) { | |
interpolations[p] = { | |
start: parseFloat( element.style[p] ) || 0, | |
end: parseFloat( properties[p] ), | |
unit: ( typeof properties[p] === 'string' && properties[p].match( /px|em|%/gi ) ) ? properties[p].match( /px|em|%/gi )[0] : '' | |
}; | |
} | |
// Takes one step forward in the animation | |
function step() { | |
// Ease out equation over the specified duration | |
var progress = 1 - Math.pow( 1 - ( ( new Date().getTime() - startTime ) / config.duration ), 5 ); | |
// Update styles to match current interpolated values | |
for( var p in interpolations ) { | |
var property = interpolations[p]; | |
element.style[p] = property.start + ( ( property.end - property.start ) * progress ) + property.unit; | |
} | |
// Repeat the above if we're not done | |
if( progress < 1 ) { | |
setTimeout( step, 1000 / 60 ); | |
} | |
else if( config.complete ) { | |
config.complete(); | |
} | |
} | |
// Start the animation | |
step(); | |
} | |
// Usage example: | |
function anim1() { | |
animate( document.querySelector( '.box' ), { | |
left: '200px', | |
top: '100px', | |
width: '100px', | |
height: '100px', | |
opacity: 1, | |
}, { | |
duration: 1000, | |
complete: anim2 | |
} ); | |
} | |
function anim2() { | |
animate( document.querySelector( '.box' ), { | |
left: '50px', | |
top: '50px', | |
width: '50px', | |
height: '50px', | |
opacity: 0.5 | |
}, { | |
duration: 1000, | |
complete: anim1 | |
} ); | |
} | |
anim1(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment