tags:

views:

25

answers:

1

I want to create the impression of a preloader for my site. I have <div class="loading"> that should fade in and out until the contents of <div id=page-wrap> are loaded.

Right now i'm using a time-based solution to guess, but of course it isn't accurate:

<script type="text/javascript">
// fade site in when loaded
$("#page-wrap").css("display", "none");
$(window).bind("load",function(){
    $("#page-wrap").fadeIn(2000);
});

// blink markers
$(".loading").hide();
$(".loading").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);
</script>

How can I make this more sophisticated and actually bind the fadeIn/fadeOut to the page loading?

+2  A: 

A bit of an odd setup, but what the hell :)

Try something like this:

<script type="text/javascript">
  $("#page-wrap, .loading").hide();
  $(window).load(function(){
    $(".loading").stop(true, true).hide();
    $("#page-wrap").fadeIn(2000);
  });
  function fadeLoop() {
    $(".loading").fadeIn(200).fadeOut(200, fadeLoop)
  }
  fadeLoop();
</script>

This does a fade loop repeating until stopped, which the .stop() will do, not calling the fadeLoop callback, and stopping the loop.

Nick Craver
Thanks Nick. I've noticed that on first load, `.loading` divs remain hidden, and if I refresh the page they show but `stop()` doesn't take effect. Very odd. Any ideas there?
thv20
@thv20 - That's very odd, you're not running this inside a `document.ready` are you? and is the `.loading` element declared *before* this script block?
Nick Craver