Really beating my head in with this one. I’ve got a variable amount of images to be loaded into the page in groups of 5. On page load, I’m trying to load the first 5 and each group after that will be added in by clicking on a link.
My logic is this:
-
make an array of all the list elements on page load
-
pass the first 10 of the array into a function that converts the li to an image and fades it into the page on window load
-
pass additional groups of 5 from the array on user click of a load more button
my code that doesn’t follow the above logic but does convert the li’s and fade them in is below:
see full commented mess on jsfiddle:
http://jsfiddle.net/danielredwood/qntMg/
thanks for your help!
function buildImg() {
$('.userGallery li').each(function(){
var loc = $(this).find('a').attr('href'),
ttl = $(this).find('a').attr('title'),
img = $('.userGallery').append($('<img/>', { class: 'user', src: loc, alt: ttl })),
usr = $('.user');
$(this).remove();
usr.each(function(i){
$(this).delay(200*i).animate({ opacity:1 },400);
});
});
}
var elm = $('.userGallery li'),
cnt = 0,
tns = [];
for(i=0;i<elm.length;i++){
if(cnt==10){
buildImg(tns);
tns=[];
}
tns[cnt++]=elm[i].image;
}
buildImg(tns);
Here’s a bit simpler way to do this. To explain,
buildImg()finds all the desired links and creates image objects for each one and puts them in an array.loadMore()loads the next 10 images into the gallery and initiates their.fadeIn()animation.loadMore()is called once initially (to load the first 10 images) and then subsequently when the loadMore button is clicked to load the next 5 each time it’s pressed.Because you only had 10 images in your jsFiddle, I duplicated them just so you could see how it works with more than 10 images.
Everything is encapsulated in a document.ready handler so that it starts when the DOM is loaded and so that our globals aren’t really globals (so they are inside a function block).
Working demo here: http://jsfiddle.net/jfriend00/h2GVz/
Here’s a bit more involved version that doesn’t start animating the images until they are loaded in case they take longer to load than their scheduled animation time. You may not need this extra complication, but I was interested in how to do it so I wrote it: http://jsfiddle.net/jfriend00/WAuuB/