Clagnut

Menu

Displaying titles for Flickr Badges

§ Photography · DOM | JavaScript · Flickr

On the Clagnut home page, in the middle column, I display a random photo. It used to be this was pulled from a photo archive on my own server, but a while ago I switched to choosing a random photo from my Flickr photostream through use of a customised Flickr Badge. I wanted to display the title below the photo, but Flickr badges don’t show photo titles, so I turned to a simple bit of DOM scripting for a solution.

Once you strip away the extraneous HTML, the Flickr Badge itself is external JavaScript call which does this:

b_txt = '
<div class="flickr_badge_image" id="flickr_badge_image1">
<a href="http://www.flickr.com/photos/clagnut/4504183/">
<img src="http://static.flickr.com/4/4504183_619bbaaf2d_m.jpg"
alt="A photo on Flickr" title="Coventry Old Cathedral"
height="180" width="240"></a></div>'
document.write(b_txt)

From this you can see the script simply writes a div containing a linked image; the only place the image title exists is in the alt attribute. And so DOM scripting comes to the rescue. The code spat out by the Flickr script includes a div with a handy id of flickr_badge_image1. So starting from there we can drill down through the DOM and get hold of that pesky alt text:

badgeDiv = document.getElementById('flickr_badge_image1');
badgeA = badgeDiv.firstChild;
badgeIMG = badgeA.firstChild;
badgeTITLE = badgeIMG.title;

And then I just write the title to the page:

document.write(badgeTITLE);

The above code is not particularly robust as it clearly depends on Flickr not changing the id or the code it spits out, that aside it works reliably (update: see Matthew Pennell’s comment for a better way of getting the text). At this juncture I should point out that using the Flickr API to get this information is a more robust method, however that involves learning the API and writing code to parse the back-and-forth. Even though classes such as phpFlickr can make life easier, it’s all a bit much for a random photo on a personal site.

So there we are, a simple bit of DOM scripting to expose some otherwise unavailable information. Next up, I will discuss a solution for making the photo scale within my liquid layout.