Search code examples
jqueryjsonflickr

flickr gallery loading pictures from specified tag


Hey I have flickr gallery and i would like to load pictures from it to a div 'gallery' but only two first pictures with a specified tag defined in a 'data-category' should be load to that div.

I have html:

    <div data-category="clouds"  class="gallery"></div>
    <div data-category="mount" class="gallery"></div>

js:

$('.gallery').each(function(index) {
    var dataCategory = $(this).attr('data-category');
    (function() {
        var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
        $.getJSON(flickerAPI, {
            tags : dataCategory,
            tagmode : "any",
            format : "json"
        }).done(function(data) {
            $.each(data.items, function(i, item) {
                var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");
                $("<img/>").attr("src", sourceSquare).appendTo(".gallery");
                if (i === 1) {
                    return false;
                }
            });

        });

    })();

});

The problem which I have is that now I load first two pictures from all specified tags into all 'gallery' divs. I supposed to load two pictures to 'gallery' but only with specified tag given in 'data-category'


Solution

  • You say .appendTo(".gallery"), which appends to all matching elements. If I've understood what you are trying to do you need to append to the individual gallery element for the current outer .each() iteration.

    Try something like this:

    $('.gallery').each(function(index, el) { // <-- add parameter for current element
        var dataCategory = $(this).attr('data-category');
        var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
        $.getJSON(flickerAPI, {
            tags : dataCategory,
            tagmode : "any",
            format : "json"
        }).done(function(data) {
            $.each(data.items, function(i, item) {
                var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");
                $("<img/>").attr("src", sourceSquare).appendTo(el); // <-- use el
                if (i === 1) {
                    return false;
                }
            });
        });
    });
    

    The $.getJSON() function is asynchronous, but its .done() function still has access to the el parameter from the containing function.

    (Note: I've removed the immediately-invoked anonymous function since it didn't seem to add any value.)