Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) AJAX and APIs Stage 4 Challenge Answer

Hazim Bora Alap
Hazim Bora Alap
15,001 Points

Getting a random input from a Json

I decided to make a website (actually it was one of my old idea for a community type o thing but decided to use it for my learning)

I changed the existing code to

    var flickerAPI = "https://api.flickr.com/services/feeds/groups_pool.gne?jsoncallback=?";
    var flickrOptions = {
      id: '15642714@N00',
       // tags: 'beard portrait',
      format: "json"
    };
    function displayPhotos(data) {


$.each(data.items, function(i,item){
    $('body').css("background-image", 'url(' + item.media.m + ')');

  });

This way I get an image from a group in flickr as a background of the webpage. But it is always giving me the same background image. I believe it needs to be updated to change it by itself. But it is kind of boring to wait for some one to upload a new image. So I want to add a random picker

I played with

    imageOf = data.items[Math.floor(Math.random()*item.length)];

but I got no result. I was wondering how can I pick a random image from the json array?

Thanks,

Zachary Green
Zachary Green
16,359 Points

have you tried this:

$.each(data.items, function(i,item){
    imageOf = data.items[Math.floor(Math.random()*item.length)];
    $('body').css("background-image", 'url(' + imageOf.media.m + ')');
Hazim Bora Alap
Hazim Bora Alap
15,001 Points

Uncaught TypeError: Cannot read property 'media' of undefined

I get this with that code ://

1 Answer

Anthony Kornmeier
Anthony Kornmeier
8,278 Points

Hazim -

The use of the $.each function is unnecessary to access a random item in the returned JSON array. Try this to replace your $.each method.

var image = data.items[Math.floor(Math.random() * data.items.length)].media.m;
$('body').css('background-image', 'url("' + image + '")');

Hope this helps.

Hazim Bora Alap
Hazim Bora Alap
15,001 Points

This worked. Thanks alot. :))