Created
April 1, 2014 16:33
-
-
Save paul-bjorkstrand/9917807 to your computer and use it in GitHub Desktop.
Show (or hide) an element until a function/promise is complete, then hide (or show) that element after the function/promise is complete.
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($) { | |
$.fn.showWhile = function(fn) { | |
var obj = this.show(); | |
var result = fn(); | |
if (typeof result.then !== "function") { | |
result = $.Deferred.resolve(fn).promise(); | |
} | |
return result.always(function() { | |
obj.hide(); | |
}); | |
}; | |
$.fn.hideWhile = function(fn) { | |
var obj = this.hide(); | |
var result = fn(); | |
if (typeof result.then !== "function") { | |
result = $.Deferred.resolve(fn).promise(); | |
} | |
return result.always(function() { | |
obj.show(); | |
}); | |
}; | |
})(jQuery); | |
(function testShowWhile() { | |
$("#during-show-while").remove(); | |
var div = $("<div id='during-show-while'>Shown until done</div>").hide().prependTo("body"); | |
div.showWhile(function() { | |
var def = $.Deferred(); | |
setTimeout(function() { | |
def.resolve("showWhile() done"); | |
}, 2000); | |
return def; | |
}).then(function(arg) { | |
console.log(arg); | |
}); | |
})(); | |
(function testHideWhile() { | |
$("#after-hide-while").remove(); | |
var div = $("<div id='after-hide-while'>Hidden until done</div>").prependTo("body"); | |
div.hideWhile(function() { | |
var def = $.Deferred(); | |
setTimeout(function() { | |
def.resolve("hideWhile() done"); | |
}, 2000); | |
return def; | |
}).then(function(arg) { | |
console.log(arg); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment