Classy Captions with jQuery and FCKEditor

October 17
blog author


Creative Director

Let's say you have a news article content type and you use FCKEditor so your non-html savvy publisher can post a story with some basic formatting. One thing they will have difficulty doing is creating a caption for any images they insert into the body. This is not to say that they couldn't just bold some text below the photo and call that the caption, but this just isn't ideal. There is no relationship between the caption and image this way.

You could just switch off FCKEditor and stick a p tag with a class below the image, but if you've ever used FCKEditor you know how ugly and unmanageable this can be. And, still there is no real 'relationship' between these two.

Here's an elegant solution. How about re-purposing the img's "alt" attribute? After all, the "alt" attribute on an image is supposed to describe what the image is. There is no character limit, and these can make great captions. Here's how you can easily set up captions in your news articles.

First you'll want to create a class called ".caption". You can style it however you want, just be sure that it doesn't have any top margin so it stays flush to the image.

.caption { 
  margin-top: 0px; background-color: #efefef; 


Here's what you'll see when you are sticking an image into the body field with FCKEditor. Fill in the "alt" field with your caption.

Now all we need to do is include some simple jQuery. Inside your node-news_article.tpl.php (or whatever your content type is called) you can add your custom javascript file.

drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/caption.js');


And now for the fun part!

Drupal.behaviors.ClassyCaptions = function(context) {  
  //Find all images in the body and run a function on each of them
  $('.body-content img').each(function(i) {
    //grab the alt attribute from the current image.
    var caption = $(this).attr('alt'); 
    //Grab the width of the image. I subtract 12 here because my caption style has 5px padding + 1px border on each side.
    var img_width = $(this).width()-12;   
    //Pop a p tag with class caption after the current img tag
    if(caption) {




And there you have it. Any questions? Just post below and I'll get back to you. I'd also love to see some links where you have implemented this!