12Jan
2010

Tags: ,

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.

Prerequisites

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.

Code Time

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.

Flickr Stream

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

Sand Soccer Jump

Source Code

The complete source code example for this blog entry can be downloaded by clicking here.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • DZone
  • FSDaily
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter
  1. 2 Responses to “Create a Photostream Using jQuery and the Flickr API”

  2. 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

  3. @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

Post a Comment