Skip to content

Instantly share code, notes, and snippets.

@paul-bjorkstrand
Created April 1, 2014 16:33
Show Gist options
  • Save paul-bjorkstrand/9917807 to your computer and use it in GitHub Desktop.
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.
(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