Created
March 2, 2011 16:01
-
-
Save jupiterjs/851153 to your computer and use it in GitHub Desktop.
A jQuery animation helper that uses CSS Animations when available.
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
steal.plugins('jquery').then(function(){ | |
var animationNum = 0, | |
//Animation events implies animations right? | |
suportsAnimations = !!window.WebKitAnimationEvent; | |
//gets teh last stylesheet or creates one | |
var getLastStyleSheet = function(){ | |
if(!document.styleSheets.length){ | |
var style = document.createElement('style'); | |
document.getElementsByTagName('head')[0].appendChild(style); | |
if (!window.createPopup) { /* For Safari */ | |
style.appendChild(document.createTextNode('')); | |
} | |
} | |
return document.styleSheets[document.styleSheets.length - 1] | |
}, | |
//removes an animation rule from a sheet | |
removeAnimation = function(sheet, name) { | |
for(var j = sheet.cssRules.length - 1; j >= 0; j--) { | |
var rule = sheet.cssRules[j]; | |
// 7 means the keyframe rule | |
if(rule.type === 7 && rule.name == name) { | |
sheet.deleteRule(j) | |
return; | |
} | |
} | |
} | |
// essentially creates webkit keyframes and points the element to that | |
$.fn.anifast = function(props, speed, callback){ | |
//default to normal animations if browser doesn't support them | |
if(!suportsAnimations){ | |
return this.animate(props, speed, callback) | |
} | |
var current = {}, //current CSS values | |
to = "", | |
self = this, | |
prop, | |
animationName = "animate"+(animationNum++) //the animation keyframe name are going to create | |
style = "@-webkit-keyframes "+animationName+" { from {"; //the text for the keyframe | |
for(prop in props){ | |
current[prop] = this.css(prop); | |
this.css(props,"") //clear property | |
style += prop+" : "+current[prop]+"; "; | |
to += prop+" : "+props[prop]+"; "; | |
} | |
style += "} to {"+to+" }}" | |
// get teh last sheet and insert this rule into it | |
var lastSheet= getLastStyleSheet(), | |
index = lastSheet.insertRule(style, lastSheet.cssRules.length); | |
// set this element to point to that animation | |
this.css({ | |
"-webkit-animation-duration" : speed+"ms", | |
"-webkit-animation-name" : animationName | |
}) | |
// listen for when it's completed | |
this.one('webkitAnimationEnd', function(){ | |
// clear old properties | |
self.css(props).css({ | |
"-webkit-animation-duration" : "", | |
"-webkit-animation-name" : "" | |
}); | |
// remove the animation keyframe | |
removeAnimation(lastSheet, animationName); | |
// call success (this should happen once for each element) | |
callback.apply(this, arguments) | |
}) | |
return this; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment