Last active
July 26, 2016 09:58
-
-
Save johnsardine/3b4eaaa0de906344759c to your computer and use it in GitHub Desktop.
jQuery add class with animation context. Like angularjs does when animating classes.
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
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); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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