Sergi
Sergi

Reputation: 71

How can I inject an image into a list of images pulling from an API using jQuery?

When viewing this url http://dl.dropbox.com/u/1550420/jquery/flickr.html, we see a list of images pulling from an API (flickr).

I’d like to inject the following image http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg into the 3rd position of my list, thus increasing the length of my list.

In summary, the list would have 1 image inserted into it at the 3rd position. The image would come from a unique url, not from the same API.

How do I accomplish that?

Here's my code, in case the link above doesn't work:

<script>
    $(document).ready(function() {
        $.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729@N22&lang=en-us&format=json&jsoncallback=?", function(data){
          $.each(data.items, function(){
            var raffie = '<a href="' + this.link + '"></a>';
            $('<li></li>')
            .append(raffie)
            .appendTo('#pic');
            $('<img />').attr('src', this.media.m)
            .appendTo('#pic');
          });
        });
    });
</script>

and here's the hard-coded html from the body:

<ul><li id="pic"></li></ul>

Upvotes: 1

Views: 137

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219938

After you're done appending all your images to the DOM, you should select the 2nd image, and insert that other image after it:

$('#pic img:eq(1)').after('<li><img src="http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg" /></li>');

Here's the fiddle: http://jsfiddle.net/LbtWJ/ .

P.S. You shouldn't be appending your images to the DOM separately, but that's besides the point.

Upvotes: 1

pixelfreak
pixelfreak

Reputation: 17834

In your code, it looks like appending li into another li, which is not allowed.

How about this. Markup looks like this: (<li> is not really necessary since we are overwriting it, but this way page validates)

<ul id="pic"><li></li></ul>

Then the JS code looks like this:

<script type="text/javascript">
    $(document).ready(function() {
        $.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729@N22&lang=en-us&format=json&jsoncallback=?", function(data)
        {
            var html = '';
            $.each(data.items, function()
            {
               // Avoid appending to document DOM multiple times to improve performance
               html += '<li><a href="' + this.link + '"><img src="' + this.media.m + '"/></a></li>')
            });
            // 3rd hardcoded image
            html += '<li><a href="#"><img src="http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg"/></a></li>';

            // Now put it into the page
            $('#pic').html(html);
        });
    });
</script>

Upvotes: 0

Related Questions