I am displaying a message box on a website. I would like to be able to have it either fadeout on click or after X seconds. The problem is that the delay()
function
This would be an ideal use for jQuery 1.5's new Deferred objects:
// a deferred object for later processing
var def = $.Deferred();
// resolve the deferred object on click or timeout
$(".close-green").click(def.resolve);
setTimeout(def.resolve, 5000);
// however the deferred object is resolved, start the fade
def.done(function() {
$(".message-green").fadeOut("slow");
});
Working demo at http://jsfiddle.net/Nyg4y/3/
Note that it doesn't matter that if you press the button the timer still fires - the second call to def.resolve()
is ignored.