views:

507

answers:

1

For a site with a lot of small thumbnail images, I wanted to use a placeholder gif while each image was loading. This requires code like the following:

  $('.this_img').each(function(){
  var $this_img = $(this);
  var $this_src =  $(this).find('.sliderImage:first').attr('src');
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
  // set minimum dimensions
  .css({
    'min-height': '35px', 
    'min-width': '40px' 
    })
  // once the image has loaded, execute this code
  .load(function () {
    // set the image hidden by default    
    $(this).hide();

    // with the holding div #loader, apply:
    $this_img
      // remove the loading class (so no background spinner), 
      .removeClass('loading')
      // then insert our image
      .prepend(this);

    // fade our image in to create a nice effect
    $(this).fadeIn();
  })

  // if there was an error loading the image, react accordingly
  .error(function () {
    // notify the user that the image could not be loaded
  })

  // *finally*, set the src attribute of the new image to our image
  .attr('src', $this_src);

This works well, with the placeholder specified in the stylesheet, but I would like to be able to tile these images if they are too short or narrow, and background CSS is the obvious way to do that, but it's not compatible with asynchronous image loading, afaik.

My Question: Is there any jQuery (or CSS3) that can be used to tile an <img> tag?

Or alternatively, is there a way to do asychronous loading of an image and then stick it into the background css attribute? That sounds a little too magical, but maybe it works.

+1  A: 

Can you post your html markup structure ? In the blind otherwise, but did you try to modifyu the containing div 's background property ?

// your callback function

function () {
    // set the image hidden by default    
    $(this).hide(); 

    // with the holding div #loader, apply:
    $this_img
      // remove the loading class (so no background spinner), 
      .removeClass('loading')
      // then insert our image
     //.prepend(this)

.css('background','transparent url("'+$this_src+'") top left repeat');

    // fade our image in to create a nice effect
    $(this).fadeIn();
  }
pixeline
This is a good answer, but the goal is to wait until an image is finished downloading, and the JS code I posted does that. As far as I can tell, there is no way to do this with the background image attribute.
jamtoday