Created
October 5, 2017 08:28
-
-
Save fbedussi/1dd900030501d84f9e89dae976b6526a to your computer and use it in GitHub Desktop.
Apply class to allow fade in and fade out management via CSS transitions, invisible elements are in "display: none" to be invisible even to screen readers
This file contains 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
(function ($) { | |
$.fn.fadeCss = function (action) { | |
try { | |
var defaultOptions = { | |
hideClass: 'hide', | |
fadeInClass: 'fadeIn', | |
fadeOutClass: 'fadeOut', | |
zeroOpacityClass: 'transparent', | |
fullOpacityClass: 'opaque', | |
transitionDuration: 500 | |
}; | |
var args = [].slice.call(arguments, 1); | |
var customOptions; | |
var callback; | |
while (args.length) { | |
switch (typeof args[0]) { | |
case 'function': | |
callback = args.shift(); | |
break; | |
case 'object': | |
customOptions = args.shift(); | |
break; | |
} | |
} | |
var options = $.extend({}, defaultOptions, customOptions); | |
var self = this; | |
if (action === 'in') { | |
clearTimeout(this.data('prevTimer')); | |
this.removeClass(options.hideClass + ' ' + options.fadeOutClass + ' ' + options.fullOpacityClass); | |
this.addClass(options.zeroOpacityClass); | |
setTimeout(function () { | |
self.addClass(options.fadeInClass); | |
}, 1); | |
let timer = setTimeout(function () { | |
self.removeClass(options.fadeInClass + ' ' + options.zeroOpacityClass); | |
if (callback) { | |
callback.call(self); | |
} | |
//self.data('prevTimer', null); | |
}, options.transitionDuration + 1); | |
this.data('prevTimer', timer); | |
return this; | |
} | |
if (action === 'out') { | |
clearTimeout(this.data('prevTimer')); | |
this.removeClass(options.zeroOpacityClass + ' ' + options.fadeInClass); | |
this.addClass(options.fullOpacityClass + ' ' + options.fadeOutClass); | |
let timer = setTimeout(function () { | |
self.addClass(options.hideClass).removeClass(options.fadeOutClass + ' ' + options.fullOpacityClass); | |
if (callback) { | |
callback.call(self); | |
} | |
//self.data('prevTimer', null); | |
}, options.transitionDuration); | |
this.data('prevTimer', timer); | |
return this; | |
} | |
throw (new Error('Only "in" or "out" actinons allowed')); | |
} catch (e) { | |
/* eslint ignore:start*/ | |
console.log(e); | |
/* eslint ignore:end*/ | |
} | |
return this; | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment