This question already has answers here:
How to attach callback to jquery effect on dialog show?
(5 answers)
Closed 8 years ago.
I want my javascript/jquery application to stop executing all animations, and only continue executing when a loading .gif is shown.
I did manage to show the loading .gif while other animations where going on, but I really need it to already show before anything else is animated.
So I fabricated a method that waits for the callback to be executed, but it doesn't work as expected.
var Shown = false;
function ShowLoadingGif() {
$("#loading").show("fast", function() {
Shown = true;
});
while(!Shown) {
//wait for callback to be executed
}
Shown = false;
}
See this JFiddle example. I would not only like to know how to properly go about solving this problem; I would also appreciate any input as to why it doesn't work as I expect it to.
Thanks in advance!
You can use something like this, using the jQuery Deferred Object ( see Docs )
var Shown = false;
function ShowLoadingGif() {
var $promise = $.Deferred();
$("#loading").show("fast", function() {
$promise.resolve("Im done");
});
$promise.done(function(data) {
// data === "Im done"
});
}
I have updated your Fiddle that now alerts when the stuff has finished as you would expect
Fiddle (http://jsfiddle.net/k5Wan/3/)
Also I have updated the code quality
var $promise = $.Deferred();
$promise.done(function() {
alert("Done...");
});
$(function() {
$("button").on("click", function() {
$("#loading").show("slow", function() {
$promise.resolve();
});
});
});
You can shorten all that:
$('#loading').show('fast', function(){
console.log('Im loaded');
}).promise().done(function(){
console.log('great loading with you!');
});
DEMO
Related
This is a followup to a question I asked yesterday. I'm having a different problem related to jquery promises.
function setOverrides2() {
var dfd = new $.Deferred();
// do something
return dfd.promise();
}
function overrideDialog1() {
var deferred = new $.Deferred();
ConfirmMessage.onConfirmYes = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.resolve();
}
ConfirmMessage.onConfirmNo = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.reject();
}
ConfirmMessage.showConfirmMessage("Do you wish to override primary eligibility?");
return deferred.promise();
}
function overrideDialog2() {
var deferred = new $.Deferred();
ConfirmMessage.onConfirmYes = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.resolve();
}
ConfirmMessage.onConfirmNo = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.reject();
}
ConfirmMessage.showConfirmMessage("Do you wish to override secondary eligibility?");
return deferred.promise();
}
setOverrides2().done(function(data) {
// shows both dialogs at once
overrideDialog().then(overrideDialog2()).then(function() {
alert("test");
});
// waits for one dialog to complete before showing the other
// overrideDialog1().done(function() {
// overrideDialog2().done(function() {
// alert("test two!");
// });
// });
});
As shown above, when I use done(), it works perfectly, but when I use then(), it shows both dialogs simultaneously. I want to be able to be able to use reject() to abort the chain the first time the user clicks the No button (defined by the onConfirmNo() callback).
The commented .done() section waits for one dialog to finish before triggering the next, but does not abort processing if the user clicks No on the first dialog.
I think I almost have this right, so if anyone can assist on this last piece of the puzzle, I'd greatly appreciate it.
Jason
overrideDialog().then(overrideDialog2())
Should be:
overrideDialog().then(overrideDialog2)
The reason done was working was because you wrapped it inside a function (which did not immediately execute)
I've found a lot of questions about deferring, promises, running javascript synchronously, etc. and I've tried numerous things already but still can't get this to work.
Edit Here's a little more explanation on the problem. fetchData has a routine that depends on all the code inside showStuff being complete. In particular, there's divs that get created using percentage of screen size, and we need to get the height of those divs so we can draw gauges inside them. fetchData is running before slideDown() is complete. Please see the additional console.log code I've added directly below.
My button onClick() calls showOverlay().
function showOverlay() {
showStuff().promise().done( function() {
console.log($("#gauge1").height()); //returns -0.5625 or something close
fetchData(); //ajax call
});
}
function showStuff() {
$("#overlay").fadeIn(200);
$("#gauges").slideDown(800);
$(".gauge").each(function() {
$( this ).show(); //unhides #gauge1 div
});
}
The error I'm getting says: cannot call method 'promise' of undefined.
I'm not showing my fetchData() function but it basically uses ajax to call a web service and then creates gauges on the screen using Raphael. If fetchData runs before the animations are complete the gauges are not displayed correctly because their size is relative to the .gauge div's.
Edit1
Neither of the examples below work. They both run without errors but return too quickly.
function showOverlay() {
showStuff().promise().done(function() {
fetchData();
});
}
function showStuff() {
var def = $.Deferred();
$("#overlay").fadeIn(200);
$("#gauges").slideDown(800);
$(".gauge").each(function() {
$( this ).show();
});
def.resolve();
return def;
}
Doesn't work either:
function showOverlay() {
$.when(showStuff()).done(function() {
fetchData();
});
}
function showStuff() {
$("#overlay").fadeIn(200);
$("#gauges").slideDown(800);
$(".gauge").each(function() {
$( this ).show();
});
}
You've 2 issues, the deferred and thats not how you run animations one after the other.
This will get you part of the way:
function showStuff() {
var deferred = $.Deferred();
$("#overlay").fadeIn(300,function(){
$("#gauges").slideDown(800,function(){
$(".gauge").show(); //doing this one after another takes more code.
deferred.resolve();
});
});
return deferred;
}
Heres the codepen: http://codepen.io/krismeister/pen/pvgKj
If you need to do sophisticated animations like this. You might find better results with GSAP.
Heres how to stagger:
http://www.greensock.com/jump-start-js/#stagger
Try to use $.when() instead:
$.when(showStuff()).done(function() {
fetchData();
});
You a) need to return something from showStuff b) should return a promise directly, so that the .promise() method is unnecessary:
function showOverlay() {
showStuff().done(function() {
fetchData();
});
}
function showStuff() {
return $("#overlay").fadeIn(200).promise().then(function() {
return $("#gauges").slideDown(800).promise();
}).then(function() {
return $(".gauge").show().promise();
});
}
This should be quite simple but I'll be darned if I can work it out. Just trying to get a div to display while my ajax is processing and then hide once done (I've put a sleep in there purely to test its working as locally it loads so fast I'm not sure if its working or not)!
The html page has this code in the script: -
$(document).ready(function(){
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
$("#loadingGIF").ajaxStop(function () {
window.setTimeout(partB,5000)
$(this).hide();
});
function partB(){
//just because
}
var scenarioID = ${testScenarioInstance.id}
var myData = ${results as JSON}
populateFormData(myData, scenarioID);
});
There is then a div in my page like so (which I can see in the source of the page just hidden): -
<div id="loadingGIF" ><img src='${application.contextPath}/images/spinner.gif' height="50" width="50"></div>
The ready code then goes off and calls this: -
function populateFormData(results, scenarioID) {
$table = $('#formList')
for(var i in results){
var formIDX = (results[i]["forms_idx"])
var formID = (results[i]["form_id"])
appendSubTable(formIDX, scenarioID, $table, formID);
}
}
Which references this multiple times calling several AJAX posts: -
function appendSubTable(formIDX, scenarioID, $table, formID) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url = "**Trust me this bits OK ;) **"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
$subTable.append(data)
}).fail(function() {
});
}
Any pointers gratefully received...
Interestingly I bunged some alerts into my ajaxstart and stop and neither show up ever so I'm missing something obvious :S When I check the console in firefox I can see that all my POSTs are completing....
You should probably add the Ajaxstart and stop global event handlers to the document node like this
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I realized my problem, I needed to register the ajaxstart and stop to the document not the div!
So instead of this: -
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
I now have: -
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I assume this is because its the document that the ajax is running against not the div although my understanding there may not be 100% accurate at least this works so please tell me if I've misunderstood this! :)
#jbl, thanks for this pointer I did this to also leave the notification on screen for a few more moments just to make sure everything is loaded.
I'm really new to jQuery but familiar with some other languages. I recently bought a quiz type script and I'm trying to add a simple 15 second timer to each question. It's only a fun quiz, so no need to worry about users playing with the javascript to increase time etc.
Basically, if a user does not pick a question within 15 seconds, it will automatically go on to the next question and the timer starts over again.
Answers have the .next tag, and when chosen it moves onto the next question as the code below shows (hopefully).
superContainer.find('.next').click(function () {
$(this).parents('.slide-container').fadeOut(500, function () {
$(this).next().fadeIn(500)
});
return false
});
The problem i have is if i use setInterval, i don't know how i can select the appropriate div again for fade it our and fade in the next one. I've tried the below code and a few similar scrappy idea's but it doesn't work, but maybe it will give a better idea of what I'm after though.
superContainer.find('.next').click(function () {
$active_count = $count;
countInterval = setInterval(function() {
$active_count--;
if($active_count <= 0){
clearInterval(countInterval);
$active_count = $count;
$(this).parents('.slide-container').fadeOut(500, function () {
$(this).next().fadeIn(500)
});
}
$('.question-timer').html($active_count);
}, 1000);
$(this).parents('.slide-container').fadeOut(500, function () {
$(this).next().fadeIn(500)
});
return false
});
I've only been using JQuery a day or two so excuse any obvious mistakes and bad code! Let me know if you need any other code or information
This is moderately tricky for a first jQuery project.
The knack (in this solution) is to factor out a goNext function that can be called in two ways - in response to a click event and in response to a 15 second setTimeout(), not setInterval().
$(function(){
var questionTimeout = null;
function goNext($el) {
clearTimeout(questionTimeout);
var $next = $el.next();
$el.fadeOut(500, function() {
if($next.length > 0) {
$next.fadeIn(500, function() {
questionTimeout = setTimeout(function() {
goNext($next);
}, 15000);
});
}
else {
afterLastQuestion();
}
});
}
function afterLastQuestion(){
alert("last question complete");
$start.show();
}
var $superContainer = $("#superContainer").on('click', '.next', function() {
goNext($(this).closest('.slide-container'));
return false;
});
var $start = $("#start").on('click', function(){
$(this).hide();
$superContainer.find(".slide-container")
.eq(0).clone(true,true)
.prependTo(superContainer)
.find(".next").trigger('click');
return false;
});
});
DEMO
The process is started by clicking a "start" link, causing the first question to be cloned followed by a simulated click on the clone's "next" link. This ensures that the (actual) first question is treated in exactly the same way as all the others.
I also included a afterLastQuestion() function. Modify its action to do whatever is necessary after the last question is answered (or times out).
You could keep the current question in a variable, resetting it on a next click and in the timer, e.g.
var $current;
superContainer.find('.next').click(function (e) {
e.preventDefault();
$(this).parents('.slide-container').fadeOut(500, function () {
$(this).next().fadeIn(500);
$current = $(this).next();
});
});
You'll just need to set it to your first question on initialisation, and remember to reset your timer on a next click
Also, it's usually preferable to use e.preventDefault() rather than return false.
I have a big problem writing a small piece of code using JS/jQuery (don't know which of these is causing the problem). Anyhow, here we go:
$('#themePicker').unbind().click(function() {
var t = $(this);
modalwindow2(t, function() {
console.log(1);
}, function(w) {
console.log(w);
});
return false;
});
and the function itself:
function modalwindow2(w, callbackOnSHow, callbackOnHide) {
if (typeof(callbackOnSHow) == 'function') {
callbackOnSHow.call();
}
// do some stuff //
$('form').submit(function() {
ajaxSubmit(function(data) {
if (typeof(callbackOnHide) == 'function') {
console.log('---------------');
console.log(data);
console.log('---------------');
callbackOnHide.call(data);
}
});
return false
});
}
The function is called modalwindow2 and I want to call a function when the modal is shown and another function when the modal will be hidden.
The first is not a problem.
The second… Well… Let's just say it's a problem. Why?
I want a parameter sent to the second function. The paramenter is an ajax response, similar to other jQuery stuff (ajax action, sortable, etc).
I hope I made myself clear enough.
Thanks!
Edit:
I'm using jQuery 1.1.2 (or 1.1.3) and upgrading or using jQuery UI is NOT a solution. I have some dependencies (interface is one of them) and i don't have enough time (nor motivation) to upgrade to 1.3 & UI 1.7.
I noticed that you have a typo on .submit:
$('form').submti(function(){
Was that just an entry error to SO?
EDIT:
Ok, so after looking at your code and doing a short test, I've come up with this (pardon the pun):
function modalwindow2(w, callbackOnShow, callbackOnHide) {
if(typeof callbackOnShow == 'function') {
callbackOnShow.call();
}
$('form').submit(function() {
if(typeof callbackOnHide == 'function') {
callbackOnHide.call(this, "second");
}
});
}
$(document).ready(function (){
$('#themePicker').click(function(){
var t=$(this);
modalwindow2(t, function() { alert("first"); }, function(x) { alert(x); });
return false;
});
});
It looks like you may have just been missing the "this" in your call() statement. Try using callbackOnHide.call(this, data);
Let me know if that works any better!
I understand what you are trying to do, but you will need to store the newly created window so that you can access it on the close callback function.
You might want to look at jQuery UI Dialog. It provides some really basic functionality for dialog windows (modal and otherwise) and handles some of the callback implementation.