Created
April 28, 2015 16:06
-
-
Save mikedamage/62f5fdd9e8d2cfd3f926 to your computer and use it in GitHub Desktop.
jQuery CSS Transition Callbacks Plugin (ES6)
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 Transition Callbacks Module | |
* by Mike Green <[email protected]> | |
*/ | |
/* jshint esnext: true, globalstrict: true, browser: true */ | |
'use strict'; | |
import $ from 'jquery'; | |
import assign from 'lodash.assign'; | |
import isArray from 'lodash.isarray'; | |
import isString from 'lodash.isstring'; | |
import includes from 'lodash.includes'; | |
import isUndefined from 'lodash.isundefined'; | |
let defaults = { | |
once: true, | |
properties: true | |
}; | |
let transEvents = [ | |
'transitionend', | |
'webkitTransitionEnd', | |
'MSTransitionEnd', | |
'oTransitionEnd' | |
].join(' '); | |
let validateProperty = (prop, list) => { | |
if (list === true) return true; | |
if (list === false || isUndefined(list)) return false; | |
let validString = isString(list) && prop === list; | |
let validArray = isArray(list) && includes(list, prop); | |
return ( validString || validArray ); | |
}; | |
let transitionWrapper = function transitionWrapper(method = 'toggleClass') { | |
return function(klass, fn = $.noop, opts = {}) { | |
return $(this).afterTransition(fn, opts)[method](klass); | |
}; | |
}; | |
let plugin = { | |
afterTransition(fn = $.noop, opts = {}) { | |
let opts = assign({}, defaults, opts); | |
return this.each((idx, el) => { | |
let $el = $(el); | |
$el.on(transEvents, function transCallback(evt) { | |
let propName = evt.originalEvent.propertyName; | |
// If our property name isn't on on the list, skip the callback but don't unbind it | |
if (!validateProperty(propName, opts.properties)) { | |
return; | |
} | |
if (opts.once) { | |
$(this).off(transEvents, transCallback); | |
} | |
return fn.call($el, evt, propName); | |
}); | |
}); | |
}, | |
transitionToggleClass: transitionWrapper('toggleClass'), | |
transitionAddClass: transitionWrapper('addClass'), | |
transitionRemoveClass: transitionWrapper('removeClass'), | |
killTransitionEvents() { | |
return this.each((idx, el) => { | |
let $el = $(el); | |
$el.on(transEvents, evt => evt.stopPropagation()); | |
}); | |
} | |
}; | |
$.fn.extend(plugin); | |
export default plugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment