Most of us want to be able to add image captions to images on our sites. Thankfully, in WordPress you can easily add or edit a caption using the standard media tools.
But, I’ve used other content management systems that did not have this feature built in. What to do? Write my own jQuery script, of course!
I was excited to find out that HTML5 provides the new
<figcaption> elements. The HTML5 spec says image captions are exactly what these elements are intended for. After doing a bit of reading on how those elements work, here is an example of the code I wanted my script to generate:
And here’s how I wanted it to look. Looks simple enough, doesn’t it? But, I soon found out things get tricky when you’re using a content management system without built-in support for captions. I still wanted it to be easy to upload and insert an image with a caption into a page.
The Solution – a jQuery Script
I wanted clients to be able to easily upload an image into their page using their content management system’s image upload dialog. Then they could mark the image as “having a caption” using a CSS class, along with supplying the caption text. Most content management systems will allow you to associate a CSS class and a
TITLE with an image when you upload it. Here’s an example using the ExpressionEngine CMS upload dialog, using “caption” as the associated CSS class:
I needed to write a JQuery script which would grab the image “marked” with that CSS class (“caption” in this example) and automatically generate the code for
<figcaption> around the original image. Here’s how the original
<img> tag would look, as inserted by the content management system:
Putting it All Together
The script is easy to use; you can get it from Github here. I called it the “Captionator.” Take a look at my example page and you’ll quickly understand how to use it. The only tricky part is that you have to wait to execute the script until all of the images have been loaded, like this:
To use it in your CMS, you’ll need to load jQuery and call the
captionate() method as the example shows. Then you can upload images using your content management system’s dialog. When you do, give the image a
caption class and enter the caption text into the
TITLE element. You can choose whatever CSS class you want; it doesn’t have to be
Use it and let me know how it works for you! If you find any bugs or think of any useful enhancements, please let me know.