Skip to content

Instantly share code, notes, and snippets.

@johnsardine
Last active July 26, 2016 09:58
Show Gist options
  • Save johnsardine/3b4eaaa0de906344759c to your computer and use it in GitHub Desktop.
Save johnsardine/3b4eaaa0de906344759c to your computer and use it in GitHub Desktop.
jQuery add class with animation context. Like angularjs does when animating classes.
jQuery.fn.extend({
addClassWithAnimationContext: function(className, callback) {
return this.each(function(index, element) {
var self = jQuery(element);
// Exit if already has class
if ( self.hasClass(className) ) {
return;
}
var selfTransitionDuration = (parseFloat(self.css('transition-duration')) * 1000);
self.addClass('before-'+className+'-add');
setTimeout(function() {
self.addClass(className);
setTimeout(function() {
self.removeClass('before-'+className+'-add');
if ( typeof callback === 'function' ) {
callback();
}
}, selfTransitionDuration);
}, 10);
});
},
removeClassWithAnimationContext: function(className, callback) {
return this.each(function(index, element) {
var self = jQuery(element);
// Exit if does not have class
if ( !self.hasClass(className) ) {
return;
}
var selfTransitionDuration = (parseFloat(self.css('transition-duration')) * 1000);
self.addClass('before-'+className+'-remove');
setTimeout(function() {
self.removeClass(className);
setTimeout(function() {
self.removeClass('before-'+className+'-remove');
if ( typeof callback === 'function' ) {
callback();
}
}, selfTransitionDuration);
}, 10);
});
}
});
@johnsardine
Copy link
Author

jQuery('.element').addClassWithAnimationContext('open');
jQuery('.element').removeClassWithAnimationContext('open');

Grabs the element transition duration and adds a class and a before-:class:-add before that time happens

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