jQuery plugin of animation using CSS3

requires jQuery, mustache

//this is a draft impl by huzhou for reference, the origin/target function must be implemented to make it work
(function($, window, undefined) {
var animation_template = "@keyframes {{animation-name}}{from{\n{{#originals}}{{name}}:{{value}};{{/originals}}}to{\n{{#targets}}{{name}}:{{value}};{{/targets}}\n}}\n@-moz-keyframes {{animation-name}}{from{\n{{#originals}}{{name}}:{{value}};{{/originals}}}to{\n{{#targets}}{{name}}:{{value}};{{/targets}}\n}}\n@-webkit-keyframes {{animation-name}}{from{\n{{#originals}}{{name}}:{{value}};{{/originals}}}to{\n{{#targets}}{{name}}:{{value}};{{/targets}}\n}}\n.{{animation-name}}-clz{position:relative;animation-name:{{animation-name}};animation-duration:{{duration}};animation-iteration-count:{{iteration}};animation-fill-mode:forwards;\n-moz-animation-name:{{animation-name}};-moz-animation-duration:{{duration}};-moz-animation-iteration-count:{{iteration}};-moz-animation-fill-mode:forwards;\n-webkit-animation-name:{{animation-name}};-webkit-animation-duration:{{duration}};-webkit-animation-iteration-count:{{iteration}};-webkit-animation-fill-mode:forwards;}";

$.fn.animate3 = function(properties, duration, completion){
var from = [],
			to = [],
			name = 'animate-' + new Date().getTime(),
			elem = $(this);
origin = function(p, v){
				var start = elem.css(p);
				return start == "auto" ? 0 : start;
			},
target = function(p, v){
				var vAsStr = "" + v,
					parts = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i.exec(vAsStr),
					end = parseFloat(parts[2]),
					unit = parts[3]||($.cssNumber[p] ? "" : "px"),
					start = parseFloat((/^([\d+.\-]+)([a-z%]*)$/i.exec(origin(p, v)))[1]);
				// If a +=/-= token was provided, we're doing a relative animation
				if (parts[1]) {
					end = ((parts[1] === "-=" ? -1 : 1) * end) + start + unit;
				}
				return end;
			};
$.each(properties, function(p, v){
from[from.length] = {name:$.camelCase(p), value:origin(p,v)};
to[to.length] = {name:$.camelCase(p), value:target(p,v)};
});

$(document.createElement('style'))
			.text(Mustache.to_html(animation_template, {'animation-name':name,'originals':from,'targets':to,'duration':duration+'ms','iteration':1})).appendTo($(document.head));
		return elem.on("webkitAnimationEnd", completion).on("animationend", completion).addClass(name + '-clz');
};
})(jQuery||$, this);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s