Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamic Css Keyframes
///Create keyframes for moving X position TranslateX
//How to use?
// import {animate} from dynamic-keyframes.js
// animate(element, from_X_pos, to_X_pos, callback_function_after_animation_finish)
export const animate = (elm, from, to, done) =>{
var animfn = "linear"
var duration = "300ms"
var direction = "forwards" ///or "backwards"
var style = document.createElement('style');
var keyFrames = 'from { transform: translate(' + from + ', 0); -webkit-transform: translate(' + from + ', 0); } to { transform: translate3d(' + to + ', 0, 0); -webkit-transform: translate3d(' + to + ', 0, 0); }';
var animName = 'anim' + Date.now();
style.textContent = '@-webkit-keyframes ' + animName + ' { ' + keyFrames + ' } @keyframes ' + animName + ' { ' + keyFrames + ' }';
document.head.appendChild(style);
function transitionEnd() {
document.head.removeChild(style);
setTranslate(elm, to);
if(done) done();
elm.removeEventListener('animationend', transitionEnd);
elm.removeEventListener('webkitAnimationEnd', transitionEnd);
}
// listen for end of transition
elm.addEventListener('animationend', transitionEnd);
elm.addEventListener('webkitAnimationEnd', transitionEnd);
elm.style.animation = elm.style.WebkitAnimation = animName + ' ' + duration + ' ' + animfn + ' ' + direction ;
}
export const setTranslate = (elm, x, y, z) =>{
var val = !x ? '' : 'translate3d(' + (x || '0') + ',' + (y || '0') + ',' + (z || '0') + ')'
elm.style.WebkitTransform = val;
elm.style.transform = val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.