Search code examples
jquerygetload

jQuery.load(function(){}) event doesn't work in collab with .get()?


So I have this script on a website i'm working on, which basically loads images from a database and puts them in a div. When all the images are loaded, I want it to fire a scroller plugin (smoothdivscroll). But I can't find a way to make the last part work.

Here is the code:

$.get("pages/photosgigs.php", { gig: $(this).attr("id")}, function(data) {
    $('#makeMeScrollableGall').html(data)
    $(window).load( function() {
        $("#makeMeScrollableGall").smoothDivScroll();
        resize();
    });
});

The php script on photosgigs.php returns a simple <img class="photo" src="..." />. I've also tried it with $("img.photo").load() which, although I know it would fire when the first image is loaded, also doesn't work. Also tried $("#makeMeScrollableGall").load(), doesn't work either.

I'm beginning to think my problem lies in the fact that my images are loaded dynamically. Is this correct?

Or am I just doing everything wrong?


Solution

  • First, window.onload is rarely ever what you'll want here. The onload event fires once when the page first loads, it won't fire again...so currently you're adding a listener for an event that's already fired and won't fire again. Instead use the load event on the image and check that it hasn't already fired (which it might have, if it's loading from cache).

    Those changes would look like this:

    $.get("pages/photosgigs.php", { gig: $(this).attr("id") }, function(data) {
      //load data, find the photo we just added
      $('#makeMeScrollableGall').html(data).find('img.photo').load(function() {
        //when the load event fires for the image, run this
        $("#makeMeScrollableGall").smoothDivScroll();
        resize();
      //loop through the loaded images (just one) but this is easier
      }).each(function() { 
         //if the image was already loaded (cached) fire the load event above
         if(this.complete) $(this).load(); 
      });
    });
    

    The .complete is checking if the image is already loaded, if it is then fire our event handler just bound by calling .load() (shortcut for .trigger('load")).