Created
August 31, 2015 03:20
-
-
Save Xion/0a9da59c44d5c9664a2c to your computer and use it in GitHub Desktop.
Interruptible fade-out DOM animation
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
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