Skip to content

Instantly share code, notes, and snippets.

@leaysgur
Created July 9, 2014 13:06
Show Gist options
  • Save leaysgur/c5fca6eea5de0299d1d4 to your computer and use it in GitHub Desktop.
Save leaysgur/c5fca6eea5de0299d1d4 to your computer and use it in GitHub Desktop.
jQuery add/removeClass with transition and callback.
(function(global, $, undefined) {
'use strict';
var doc = global.document;
// まずイベント名を確定させる
var TRANSITION_END = (function() {
var events = {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
};
var evName, prop;
for (prop in events) {
if (typeof(doc.body.style[prop]) !== undefined) {
evName = events[prop];
break;
}
}
return evName;
}());
// そして拡張
$.extend($.fn, {
/**
* addClassして、そのtransitionEndでコールバック
*
* @param {String} className
* addClassするクラス名
* @param {Function} callback
* transitionEndで発火したいコールバック
*/
addClassWithTransitionCallback: function(className, callback) {
if (!className) { return this; }
if (!callback || !$.isFunction(callback)) {
return this.addClass(className);
}
return this
.one(TRANSITION_END, function(ev) {
callback.call(this, ev);
})
.addClass(className);
},
/**
* removeClassして、そのtransitionEndでコールバック
*
* @param {String} className
* removeClassするクラス名
* @param {Function} callback
* transitionEndで発火したいコールバック
*/
removeClassWithTransitionCallback: function(className, callback) {
if (!className) { return this; }
if (!callback || !$.isFunction(callback)) {
return this.removeClass(className);
}
return this
.one(TRANSITION_END, function(ev) {
callback.call(this, ev);
})
.removeClass(className);
}
});
}(window, jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment