afunduk
afunduk

Reputation: 9

jquery: How do i fade in on load each image in an array of images?

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:

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.

Upvotes: 0

Views: 536

Answers (2)

Sharkham
Sharkham

Reputation: 21

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".

Upvotes: 0

Diego ZoracKy
Diego ZoracKy

Reputation: 2285

['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");
    });

});

Upvotes: 0

Related Questions