user3701718
user3701718

Reputation:

use jQuery to loop through array containing img urls and append to div

I am attempting to use jQuery to append a single image from a series of images to the bottom of a div, with the number of divs being theoretically infinite, so the images have to repeat.

To do this, I've tried creating an array with a list of the image URLs, and then appending a img to divs with class .entry, with the src="" of the image taken from the array.

My code: JSFiddle Link

function mascot_aside(){        
    $('.entry').each(function(i){
    var mascots = [
"http://i454.photobucket.com/albums/qq268/Princess_Kally/negi_chisame.gif",
"http://i454.photobucket.com/albums/qq268/Princess_Kally/negi_chachamaru.gif",
"http://i454.photobucket.com/albums/qq268/Princess_Kally/negi_eva.gif",
    ];

    $(this).append('<img src='mascots[i % mascots.length]' class="mascot" />'); 
    }); 
}

mascot_aside();

I've seen this stackoverflow question, however, the problem with the answer code is if you have more divs than images, an "undefined" image loads.

Anyways, the images don't even seem to appear and I have no idea what I'm doing, so any help would be greatly appreciated. Thanks!

Upvotes: 0

Views: 1770

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Just Found some two errors in your code,

  1. Declare array outside the iteration. (Not an issue but it should not be like this)
  2. Having problem with value concatenation

Try,

function mascot_aside() {
    var mascots = [
        "http://i454.photobucket.com/albums/qq268/Princess_Kally/negi_chisame.gif",
        "http://i454.photobucket.com/albums/qq268/Princess_Kally/negi_chachamaru.gif",
        "http://i454.photobucket.com/albums/qq268/Princess_Kally/negi_eva.gif", ];

    $('.entry').each(function (i) {

        $(this).append('<img src=' + mascots[i % mascots.length] + ' class="mascot" />');
    });
}

DEMO

Upvotes: 1

Related Questions