Skip to content

Instantly share code, notes, and snippets.

@zerosignalproductions
Last active January 4, 2016 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerosignalproductions/8678737 to your computer and use it in GitHub Desktop.
Save zerosignalproductions/8678737 to your computer and use it in GitHub Desktop.
New animation function to auto switch between CSS and JS animation depending on browser support
// Updated: 01/28/2014
// Changes:
// Removed all non animation specific code
// Updated to allow passing in of positioning
var cssAnimation = (function($) {
var speed = 250,
easing = 'linear',
cssTransition = 'cubic-bezier(0.39, 0.575, 0.565, 1)',
done = false,
animationCompleteCallback = $.noop,
defaultProperties = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
return {
setup: function(element) {
var $element = $(element);
if(this._isCssAnimation()) {
$element.addClass('css3-animation')
.css(this._getVendorPrefix('transition'), this._getVendorPrefix('transform') + ' ' + speed + 'ms ' + cssTransition)
.css(this._getVendorPrefix('transform'), 'translate3d(0, 0, 0)');
}
$element.data('defaultPosition', $element.css('position'));
},
animate: function(element, properties, animationCompleteCallback) {
properties = $.extend({}, defaultProperties, properties);
var $element = $(element);
if (!$element.is(':animated')) {
if(this._isCssAnimation()) {
$element.css(this._getVendorPrefix('transition-duration'), speed + 'ms ')
.css(this._getVendorPrefix('transform'), 'translate3d(' + properties.left + 'px, ' + properties.top + 'px, 0)');
//This is the callback event for css animation
$element.on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
done = true;
animationCompleteCallback($element);
$element.off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend');
});
} else {
//Animate and call the callback event when complete
$element.animate(properties, speed, easing, animationCompleteCallback);
}
}
},
_isCssAnimation: function() {
//Mimic modernizr
return (function() {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition',
v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'];
if(typeof s[p] === 'string') {
return true;
}
p = p.charAt(0).toUpperCase() + p.substr(1);
for(var i = 0; i < v.length; i++) {
if(typeof s[v[i] + p] === 'string') {
return true;
}
}
return false;
}());
},
_getVendorPrefix: function(property, isJavascript) {
if(!window.getComputedStyle) {
return property;
}
var styles = window.getComputedStyle(document.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1];
if(isJavascript) {
return pre + property;
} else {
return '-' + pre + '-' + property;
}
}
}
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment