Skip to content

Instantly share code, notes, and snippets.

@omniosi
Created March 13, 2014 20:50
Show Gist options
  • Save omniosi/9536730 to your computer and use it in GitHub Desktop.
Save omniosi/9536730 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin - rAF test</title>
<style>
#elm{
background: lightblue;
width: 20px;
height: 20px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="elm"></div>
<button>start</button>
</body>
</html>
function animateLeft(elm, from, to, done){
var style = document.createElement('style');
var keyFrames = 'from { transform: translate(' + from + ', 0); -webkit-transform: translate(' + from + ', 0); } to { transform: translate(' + to + ', 0); -webkit-transform: translate(' + to + ', 0); }';
var animName = 'anim' + Date.now();
style.textContent = '@-webkit-keyframes ' + animName + ' { ' + keyFrames + ' } @keyframes ' + animName + ' { ' + keyFrames + ' }';
document.head.appendChild(style);
function transitionEnd(){
elm.style.animation = elm.style.WebkitAnimation = '';
document.head.removeChild(style);
setTranslate(elm, to);
done();
elm.removeEventListener('animationEnd', transitionEnd);
elm.removeEventListener('webkitAnimationEnd', transitionEnd);
}
//listen for end of transition
elm.removeEventListener('animationEnd', transitionEnd);
elm.removeEventListener('webkitAnimationEnd', transitionEnd);
elm.style.animation = elm.style.WebkitAnimation = animName + ' 3s linear forwards';
}
function setTranslate(elm, left, top){
var val = 'translate(' + (left || '0') + ',' + (top || '0') + ')';
elm.style.WebkitTransform = val;
elm.style.transform = val;
}
var box = document.querySelector('#elm');
document.querySelector('button').addEventListener('click', function(event){
animateLeft(box, '0px', '300px', function(){
log('Done!');
});
event.preventDefault();
});
function log(msg){
var div = document.createElement('div');
div.textContent = msg;
document.body.appendChild(div);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment