Skip to content

Instantly share code, notes, and snippets.

@Jpunt
Last active December 18, 2015 04:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jpunt/5727824 to your computer and use it in GitHub Desktop.
Save Jpunt/5727824 to your computer and use it in GitHub Desktop.
Patch for $.animate to use $.transit when possible, and provide fallbacks for things like translateX/Y.
/*globals $ */
/*
* Patches the jQuery-animate method to use CSS-transitions when possible.
*
* - Depends on $.transit: http://ricostacruz.com/jquery.transit/
* - Degrades gracefully to the original method when transitions aren't supported.
* - Provides fallbacks for translateX/Y's, so { x:10, y:10 } (very smooth) will become { top:10, left:10 } (less smooth) for less capable browsers.
* - 3d-transforms could be enabled with enable3d:true. Example: { x:100, enable3d:true }
* - Transitions could be disabled with enableTransitions:false. Example: { x:100, enableTransitions:false }
*/
(function() {
"use strict";
var jqAnimate = $.fn.animate;
$.fn.animate = function() {
var args;
if( supported(arguments) ) {
args = prepArgs('transit', arguments);
$.fn.transit.apply(this, args);
} else {
args = prepArgs('jquery', arguments);
jqAnimate.apply(this, args);
}
};
function supported(args) {
if(!$.support.transition)
return false;
// disabled by argument
if(args[0].enableTransitions === false || (args[1] && args[1].enableTransitions === false))
return false;
// Scroll-animation is not supported
if(typeof args[0].scrollTop !== 'undefined')
return false;
// show/hide/toggle-values are not supported
for(var key in args[0]) {
if($.inArray(args[0][key], ['show', 'hide', 'toggle']) > -1)
return false;
}
return true;
}
function prepArgs(type, args) {
if(typeof args[0] !== 'object')
return args;
// Transit-specific properties
if(type === 'transit') {
// Shortcut to enable 3d-transforms
if(typeof args[0].rotate3d === 'undefined' && args[0].enable3d === true)
args[0].rotate3d = '0,0,0,0deg';
}
// jQuery-specific properties
if(type === 'jquery') {
// Fallback for 2d-transforms
if(typeof args[0].x !== 'undefined') args[0].left = args[0].x;
if(typeof args[0].y !== 'undefined') args[0].top = args[0].y;
delete args[0].x;
delete args[0].y;
}
// Cleaning up extra properties
delete args[0].enable3d;
delete args[0].enableTransitions;
// Done
return args;
}
})();
@remcoder
Copy link

remcoder commented Jun 7, 2013

Why not set enable3d to true per default? That's what you want most of the time, no?

@hermanbanken
Copy link

You should keep it chainable. Return this in $.fn.animate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment