Recently I added a Flickr photostream to the footer of the home page of this blog and I thought it would be cool to post an entry on how you can use jQuery and the Flickr API to do the same. Even if you’re not familiar with jQuery or the Flickr API it’s actually quite simple to accomplish this task.
Download jQuery
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animation, and Ajax interactions for rapid web development.
Download jQuery lightBox
jQuery lightBox is a jQuery plugin that can be used to display a gallery of images on the current page using the power and flexibility of jQuery’s selectors.
Create a Flickr Account and API Key if you don’t already have them
A Flickr API key is necessary for accessing additional service features offered by Flickr.
Let’s assume that our HTML page is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"
lang="en-US" xml:lang="en-US">
<head>
<title>JQuery/Flickr API Code</title>
<link rel="stylesheet" href="styles/style.css"
type="text/css" media="screen" />
<link rel="stylesheet" href="styles/jquery.lightbox-0.5.css"
type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.lightbox-0.5.min.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
</head>
<body>
<!-- Some Content -->
<div id="footer">
<div id="flickr"></div>
</div>
</body>
</html>
There are only a few important things to be aware of with this code. First we need to make sure that we include all of our style sheets and JavaScript files in the head section of our HTML page. In addition to including the jQuery and jQuery lightBox files notice that I have also created a style sheet called “style.css” and a JavaScript file called “custom.js“. We will use these files to store our custom code.
Flickr has a very extensive API that allows developers to grab images using many different techniques. For this example I have chosen to pull back images using the flickr.photos.search method. This method – among other things – allows users to grab images that have been labeled with a specific tag.
In the custom.js file we will include the following code:
$(function() {
var apiKey = '<YOUR API KEY>';
var userId = '<FLICKR USER ID>';
var tag = '<COMMA SEPERATED LIST OF TAGS>';
var perPage = '25';
var showOnPage = '6';
$.getJSON('http://api.flickr.com/services/rest/?format=json&method='+
'flickr.photos.search&api_key=' + apiKey + '&user_id=' + userId +
'&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?',
function(data){
var classShown = 'class="lightbox"';
var classHidden = 'class="lightbox hidden"';
$.each(data.photos.photo, function(i, rPhoto){
var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
+ rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;
var thumbPhotoURL = basePhotoURL + '_s.jpg';
var mediumPhotoURL = basePhotoURL + '.jpg';
var photoStringStart = '<a ';
var photoStringEnd = 'title="' + rPhoto.title + '" href="'+
mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' +
rPhoto.title + '"/></a>;'
var photoString = (i < showOnPage) ?
photoStringStart + classShown + photoStringEnd :
photoStringStart + classHidden + photoStringEnd;
$(photoString).appendTo("#flickr");
});
$("a.lightbox").lightBox();
});
});
Let’s examine the variables that are declared at the top of this JavaScript file:
apiKey – Your Flickr API key
userId – User ID of the user whose pictures you wish to grab
tag – A comma separated list of tag values
perPage – The number of images you wish to pull back (maximum: 500)
showOnPage – The number of images you wish to display on the page
Next we call jQuery’s $.getJson method passing it a custom URL and a callback method. The URL is dynamically created based on the values set in the variables mentioned above. The callback method takes the JSON object returned by Flickr and parses it to grab the relevant photo data. The JSON returned by Flickr might look something like this:
jsonFlickrApi({"photos":{"page":1, "pages":1, "perpage":25, "total":"17",
"photo":[{"id":"42626017633f", "owner":"705311402@N00",
"secret":"2casd5d2079e", "server":"4010", "farm":5, "title":"Some Photo Title",
"ispublic":1, "isfriend":0,"isfamily":0}, {"id":"42626017633f",
"owner":"705311402@N00", "secret":"2casd5d2079e", "server":"4008",
"farm":5, "title":"Some Other Photo", "ispublic":1, "isfriend":0,
"isfamily":0}, ...]}, "stat":"ok"})
Using the jQuery $.each method we can easily iterate through all of the photo elements and create the dynamic HTML needed to add the photostream to our HTML page. For each photo, we grab its relevant information (id, server location, title, etc.) and build image links with the following structure:
<a class="lightbox"
href="http://farm5.static.flickr.com/4010/42626017633f _2casd5d2079e.jpg"
title="Some Photo Title">
<img alt="Some Photo Title"
src="http://farm5.static.flickr.com/4010/42626017633f _2casd5d2079e_s.jpg"/>
</a>
These images will be appended to the div with the ID of “flickr” on our HTML page. The jQuery $.append method is used to accomplish this task. Notice that we end the “thumbnail” photo URLs with “_s“. This will request a small square shaped version of our image from Flickr which is perfect for display in a photostream.
Each image will have a CSS class of “lightbox” so that we can properly select all of the images to be used by the jQuery lightBox library. Notice that the callback function passed into the $.each method stores a loop counter variable called “i“. Since we only want 6 images displayed on our page at once we can use this counter variable to check the current loop position and add an additional CSS class called “hidden“” to the images not within the first 6 photos returned. These photos will be added to the page, but will not be visible to the user.
After we add all of the images to the page we call $("a.lightbox").lightBox(); to create a Lightbox for all of the images (including the hidden ones) in our photostream.
When we view the page we will see the first 6 images in our photostream.

Clicking on any of the images will launch a Lightbox and allow us to scroll through the remaining photos.

The complete source code example for this blog entry can be downloaded by clicking here.
13 Responses to “Create a Photostream Using jQuery and the Flickr API”
Really helpful post, thanks for writing this up! Your directions were really clear and this approach worked great. I’m finding that calls to the Flickr API aren’t always very fast, though, so I’m looking into applying some sort of preloader/spinner thing to my images. Any suggestions for a good method for implementing that?
By Sarah on Feb 21, 2010
@Sarah
Thanks for the kind words.
I checked out your site. You can simply place a “span” element with an animated gif/loading text/whatever inside of your div with the id of “flickr”. Give this span an id of something like “loading”. Once the images are pulled back from Flickr (i.e. at the end of the $.getJSON method) you can use JQuery to remove the span element and then show your pictures using the following command:
$(“#loading”).remove();
Check out the source and jwwl.js JavaScript file on this page for an example:
http://www.sixtysixeast.com/jwwl/content.html
By Justin Spradlin on Feb 21, 2010
I’m looking at building in a refresh function for the flickr div so any new images up loaded to flickr automatically show up in the div when it refreshes.
I think i’ve got it right
var refreshId = setInterval(function()
{
$(‘#flickr’).fadeOut(1500).load().fadeIn(1500);
}, 5000);
Also the link to you loading example (http://www.sixtysixeast.com/jwwl/content.html) doesn’t work this would be really useful to implement if the container div is set to refresh
Thanks
By Matt on Apr 14, 2010
@Matt
Thanks for the heads up about the broken link. I’ve fixed it so you can now check out the source.
Just one quick note: I’ve noticed sometimes that it takes up to 10 minutes for the images I upload to flickr to be available via the API. Just something to keep in mind.
By Justin Spradlin on Apr 14, 2010
I’m still a little unclear on the api key and the tags.
As this is your plug-in should i be usinging your api key or do i need to apply for my own even though i did not develop this plugin?
I tried adding a tag to some of my photos, i used the tag golf in flickr and change the tag like to var tag = ‘golf’; but it’s not working as i thought it should, if i add the tag to the script it fails to load in any images at all.
Last question…. honest!! How do i go about adding more than one flickr stream to a page?
Thanks
By Matt on Apr 19, 2010
@Matt
Thanks for the comment. You should get your own API key from flickr for interacting with your flickr account.
I’ve noticed that it can sometimes take about 10 – 15 minutes for the tagged images to become available to the API. So once you tag images in Flickr wait a little while before expecting to see the images to show up in your photostream.
If you want to add more than one flickr stream to a page you should just be able to add multiple DIVs with different IDs and use jquery to place the images in the appropriate place.
For example if you had a DIVs identified by the IDs car, boat, plane. You could grab those images from Flickr using tags of the same name then use jquery and the code about to append the photostreams to those divs:
$(carPhotoString).appendTo(“#car”);
$(boatPhotoString).appendTo(“#boat”);
$(planePhotoString).appendTo(“#plane”);
I hope this helps. Good luck!
By Justin Spradlin on Apr 19, 2010
Hi Justin,
I’m trying to implement your script and get an error “data.photos” is undefined. And so I don’t get any photos. (My site is not published yet.) What can I do? Thanks in advance!
By Katja on May 25, 2010
@Katja
It’s a little hard to answer your question without seeing your code, but here are a few possible tips:
1. Make sure that the data object is not null. Use an alert statement to print out its contents: alert(data)
2. Make sure your API key, url, and tag strings are all correct.
By Justin Spradlin on May 25, 2010
Justin, thanks for your reply.
The temporary address is http://student.cmd.hro.nl/0825320/jaar2/Darkroom/template. I don’t get errors anymore, but I don’t have any stream either. I don’t really understand that “data object” stuff.
By Katja on May 26, 2010
Hello Katja,
One thing I noticed was that when I construct your URL call into flickr I see that the JSON that is returned does not reference any photos:
http://api.flickr.com/services/rest/?format=json&method=flickr.photos.search&api_key=1cc94fa73b96447769167da4390183e5
&user_id=28214005@N02&tags=architecture&per_page=10&jsoncallback=?
Contrast that with the JSON that is returned from the URL that I call into:
http://api.flickr.com/services/rest/?format=json&method=flickr.photos.search&api_key=13ee651e2a7464fb55ac71807a23b5ea
&user_id=70511402@N00&tags=justinspradlindotcom&per_page=25&jsoncallback=?
Lots of JSON with photo information is returned. I think once you get the correct JSON returning from Flickr everything will work for you. Let me know how it goes. Good luck!
By Justin Spradlin on May 27, 2010
You can create your own api server for advanced operations using jQuery.getJSON() and access it from any other domain (cross-domain). Here is a detailed tutorial explaining how actually $.getJSON() works for JSONP:
http://abcoder.com/javascript/jquery/jsonp-first-timer/
Hope it’ll help.
Thanks
By ABM Adnan on Jun 27, 2010
Hi Justin,
I really like the idea of this so I decided to give it a go despite knowing nothing at all about JS or API or STYLES or the internet in general. I just tried to create a blank page with the div layer showing the 6 images like you have as your footer but all I get is a blank page…
Any ideas from looking at my page what I might be doing wrong?
Many thanks,
By Iain on Jul 19, 2010
Hi Justin,
Please ignore my earlier question, I have sorted it now.
I was using my screen name instead of the user ID.
Thanks very much for the tutorial, it will prove very useful!
Kind regards
Iain
By Iain on Jul 19, 2010