1

I've got the following function which retrieves a .php file's contents and displays it in a div. The retrieval part works great, but i would like to show a spinner for e.g. 1 second.

Here's my JQuery function:

function f(par){
$("#load").show();
$.ajax({url: par + ".php",
success: function(result){
    $("#info").html(result);
    $("#info").css("top", Math.max(0, (($(window).height() - $("#info").outerHeight()) / 2) + $(window).scrollTop()) + "px");
    $("#info").css("left", Math.max(0, (($(window).width() - $("#info").outerWidth()) / 2) +   $(window).scrollLeft()) + "px");
    $("#info").delay(1000).show(0);
    }});
$("#load").hide();
};

Load here is the div with the spinner in it and info displays well.. the retrieved info! The master plan is to delay (because the retrieval takes no time at all) the show(0) function, to let the spinner run at least 1 second.

The css is as followed (from How can I create a "Please Wait, Loading..." animation using jQuery?):

#load {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('http://sampsonresume.com/labs/pIkfp.gif')
                50% 50% 
                no-repeat;
}

#info{
display: none;
position: fixed;
z-index: 500;
height: 40%;
width: 60%;
overflow: auto;
background: rgba(0, 190, 0, .8);
}

I've aso tried to use $(this).addClass("load"); but that didn't work either.

What goes wrong?

Solution:

(for those interested) Thanks to j08691 the solution was quite simple:
setTimeout(function() {
        $("#info").show();
        $("#load").hide();
    }, 1500);
Community
  • 1
  • 1
Gooey
  • 4,740
  • 10
  • 42
  • 76
  • 1
    What happens if you comment out `$("#load").hide();`? – j08691 Jul 18 '12 at 14:57
  • O_O Okay the spinner shows itself now, so there must be a problem with the delay part, as the .hide() triggers instantly after the .show() – Gooey Jul 18 '12 at 15:00
  • Your hide occurs after the show because it's not in the ajax callback. – j08691 Jul 18 '12 at 15:00
  • I had it in the ajax part before, just after the delay(1000) part. But that didn't do the trick. – Gooey Jul 18 '12 at 15:01
  • 1
    `.delay()` is for effects, not callbacks. Use setTimeout instead to create a delay. – j08691 Jul 18 '12 at 15:02
  • Did the job :) I can't accept comments as good answers so if you'd make answer i can vote it ;) – Gooey Jul 18 '12 at 15:05

1 Answers1

1

You need to move the $("#load").hide(); statement into the callback of the ajax request since the way it is now will trigger it right after $("#load").show();. Also, .delay() is for effects and not for callbacks. Use a setTimeout() call instead.

j08691
  • 204,283
  • 31
  • 260
  • 272