Created
March 13, 2014 20:50
-
-
Save omniosi/9536730 to your computer and use it in GitHub Desktop.
animating with javascript. taken from http://coding.smashingmagazine.com/2013/03/04/animating-web-gonna-need-bigger-api/
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
<!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> |
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
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