0

I'm really new to Jquery, however, i've done research and tried hard to do this. I have successfully made one image to do what i want:

  • preload the image( img = new Image(); $(img).attr('src', someurl);)
  • append it to a container
  • fade in the image ( using .hide() and .fadeIn(500) )
  • on load add some class and hide a .gif image with the loading animation

using this code:

var img = new Image();
$(img).attr('src', 'images/thumbnails/thumb1.png').attr('alt', 'thumbnail' + 1);
$(img).appendTo($('.thumbnail')).hide().fadeIn(400);
$('.thumb img').load(function(){
  $('.loader').fadeOut(300);
  $(this).addClass("thumbimage");
});

where .loader is class added to a div that shows the loading.gif animation.

Now, what i want to achieve is to implement this on an array of image srcs and this is what i have so far:

var imagesrc = [ someurl, someurl, ... ];
$(document).ready(function(){
 var arr = new Array();
 function loadimage() {
  for (i = 0; i < imagesrc.length; i++) {
   arr[i] = new Image();
   $(arr[i]).attr('src', imagesrc[i]);
   $(arr[i]).attr('alt', 'thumbnail' + i);
   $(arr[i]).hide().appendTo($('.thumbnail').eq(i)).fadeIn(300);
  }
 }
 loadimage();
    $('.thumbnail img').load(function(){
  var par = $(this).parent();
  var row = par.parent();
  var indexrow = row.index('.thumbrow');
  var thumbindex = par.index('.thumb') + 3*indexrow;
        //^ this calculates which loading.gif div to fade out
  $('.loader').eq(thumbindex).fadeOut(200);
  $(this).addClass("thumbimage");
 });
});

I've also tried to move the .append() into the .load(..) and failed.

afunduk
  • 9
  • 1

2 Answers2

0
['url1', 'url2'].forEach(function(imageUrl){

    var img = new Image();
    $(img).attr('src', imageUrl).attr('alt', 'thumbnail' + 1);
    $(img).appendTo($('.thumbnail')).hide().fadeIn(400);
    $('.thumb img').load(function(){
      $('.loader').fadeOut(300);
      $(this).addClass("thumbimage");
    });

});
Diego ZoracKy
  • 2,227
  • 15
  • 14
0

There may be some confusion with ".thumbnail img", "thumbimage". and "thum img". Are all three separately being used correctly, as you laid them out?

At the end, instead of "thumbimage" in $(this).addClass("thumbimage"); you may want to use "thumb img".

Sharkham
  • 21
  • 3