views:

84

answers:

1

I've run into a bit of a problem and was hoping to get a little help. I am trying to select a random image from a flickr set and append it to a div to use as a background image. Here is the function:

$.getJSON("http://***", function (data){                                                                                                                                   

    var htmlString = ""; 

    $.each(data.photoset.photo, function(i, item){      

            var bkg = data.photoset.photo[i];
            var randomBkg = Math.floor(Math.random() * bkg.length);

            htmlString += '<img src='+ randomBkg.url_o +' />';

    return i < 0;   

    });     

    $('#bg').append(htmlString);

 });

If i replace randomBkg.url_o with bkg.url_o it just returns the first image in the set. using it as i have above appends an image tag with "undefined" as the img src. Any help about where i am misguided would be super appreciated.

A: 

The image tag is "undefined" right now, because Math.floor returns a Number, and Numbers don't have the url_o property. If you are just looking to pick out one image out of the set, you don't really need to use $.each to iterate over all of the items. You should be able to do the following:

var index = Math.floor(Math.random() * data.photoset.photo.length);
var randomImage = data.photoset[index];
var htmlString = = '<img src='+ randomImage.url_o +' />';
Raul Agrait
Had to specify that i was looking for a photo out of the photoset on randomImange, but this worked great. Cheers.edited for clarity.
cley
Cool. Can you click on the up arrow next to my answer if it was helpful? Thanks!
Raul Agrait
yeah you got it. i'm new here. edit - seems i need 15 reputation to vote up. Will circle back to take care of this once i have the reputation.
cley