Last active
February 17, 2019 03:42
-
-
Save dagalti/8e237a344fd224f9472d0e8b434698e6 to your computer and use it in GitHub Desktop.
Dynamic Css Keyframes
This file contains 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
///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