Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Interruptible fade-out DOM animation
function interruptibleFadeOut(element, options) {
if (typeof options === 'number') {
options = {fadeOut: options};
}
element = $(element);
return new Promise(function(resolve) {
// Event handlers used by the effect.
var events = {
mouseenter: function() { interruptAnimation(); },
mouseleave: function() { delayedFadeOut(); },
click: function() {
interruptAnimation();
delayedFadeOut();
},
};
Object.keys(events).forEach(function(name) {
element.on(name, events[name]);
});
// Helper functions.
var interruptAnimation = function() {
element.stop(true);
element.css('opacity', 1.0);
};
var delayedFadeOut = function() {
if (options.delay) {
element.delay(options.delay);
}
element.fadeOut(options.fadeOut, function() {
Object.keys(events).forEach(function(name) {
element.off(name, events[name]);
});
resolve();
});
};
// Start the animation.
if (options.fadeIn) {
element.fadeIn(options.fadeIn);
}
delayedFadeOut();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.