Chill Web Designs
Chill Web Designs

Reputation: 1331

jQuery how to append images to more than one div

I am using jquery json to return images from flickr. If I want to append all the image to one div thats not a problem. What i want to do is return 36 images but append 1-9 images to div one and 10-18 to div two 19-27 to div three and 28-36 to div four.

Upvotes: 1

Views: 297

Answers (1)

user113716
user113716

Reputation: 322492

This should do it:

Example: http://jsfiddle.net/9KyaK/

$images.each(function( i ) {
    if( i % 9 === 0 )
        $images.slice(i, i + 9).appendTo('#div' + (i / 9) );
});

Assumes $images is the collection of images, and each div has an id of div0', 'div1 etc.


EDIT: I had .appendTo('#div' + i ); instead of .appendTo('#div' + (i / 9) );. Fixed and added an example.


EDIT: For your specific code, add this to the end of the getJSON callback. After the for loop.

var $flickr = $('#flickr'); 
var $images = $flickr.children('a');

$images.each(function( i ) {
    if( i % 9 === 0 ) {
        var newDiv = $('<div/>',{id:'div'+(i/9)}).appendTo($flickr);
        $images.slice(i, i + 9).appendTo( newDiv );
    }
});

Upvotes: 3

Related Questions