Roshi
Roshi

Reputation: 396

Instagram API - get images using jquery

I made an AJAX function that get the four latest images of my Instagram account. Now I want to make an append function that inserts my two first images in a <div> called insta-left and the two others in a second <div> called insta-right, but I can't find a solution to split my function:

var token = 'MY_TOKEN', 
    userid = MY_USER_ID,
    num_photos = 4; // number of photos i get

$.ajax({
    url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent',
    dataType: 'jsonp',
    type: 'GET',
    data: {
        access_token: token,
        count: num_photos
    },
    success: function(data) {
        console.log(data);
        for (x in data.data) {
            $('.insta-left').append('<img src="' + data.data[x].images.low_resolution.url + '">');
        }
    },
    error: function(data) {
        console.log(data);
    }
});

If I do it like this all images will be inserted into insta-left. How can I split my function to get the two first photos in this <div> and the two latest in an other <div>?

Upvotes: 1

Views: 1632

Answers (2)

DJ_Icebear
DJ_Icebear

Reputation: 232

How about doing a regular for loop and checking the index?

success: function(data) {
console.log(data);
    for (i = 0; i < data.data.length; i++) {
        if (i < 2) {
            $('.insta-left').append('<img src="' + data.data[i].images.low_resolution.url + '">');
        } else {
            $('.insta-right').append('<img src="' + data.data[i].images.low_resolution.url + '">')
        }
    }

You might also want to think about the case when the Instagram API returns fewer than your requested number of photos.

Upvotes: 3

Ivan Arambula
Ivan Arambula

Reputation: 124

You could try something like

for(i = 0; i < 2; i++) {
  $('.insta-left').append(...);
}

for(i = 2; i < 4; i++) {
  $('.insta-right').append(...);
}

You can access the the images with data.data[i].

Also, it might be a good idea to run some checks so that it doesn't try to append images that don't exist. Something like,

if(typeof data.data[i] !== 'undefined') { ... }

Upvotes: 1

Related Questions