cat
cat

Reputation: 1587

Jquery: Is there something wrong with my .load()?

I have a problem with this code...
The preloader shows up when this function is fired, but it never hides.
The page also shows up before the image inside it is finished loading.

Is there something wrong with my load function?

$('select.select').change(function() {

    var x = $(this).val();

    //Hide the current page and show the preloader
    $('#page' + x).hide();
    $('#pageLoader *').show();

    //when current page is loaded, hide preloader and show page
    $('#page' + x + ' img').load(function() {
      $('#page' + x).show();
      $('#pageLoader *').hide();
    });

});

Upvotes: 0

Views: 115

Answers (3)

Nick Craver
Nick Craver

Reputation: 630379

If the <img> already has a src attribute you need to loop through and check in the case it comes from cache, like this:

$('#page' + x + ' img').one('load', function() {
  $('#page' + x).show();
  $('#pageLoader *').hide();
}).each(function() { 
  if(this.complete) $(this).load();
});

Upvotes: 1

William Niu
William Niu

Reputation: 15853

You need to provide a url as the first parameter of the load() function.

See documentation.

Upvotes: 0

Andy E
Andy E

Reputation: 344537

If the <img> element is being created after the event handler is set you will need to bind the handler using live() instead, which will bind to existing and future elements matching the selector on the page:

$('#page' + x + ' img').live("load", function() {
  $('#page' + x).show();
  $('#pageLoader *').hide();
});

http://api.jquery.com/live/

Upvotes: 1

Related Questions