Expanding on How to Auto Caption Images Using MooTools

Posted at 9:31 PM on January 23rd, 2009

One of the guys I love chatting it up with is Jacob Gube of Six Revisions. Jacob recently posted a great Mootools tutorial on automatically adding image captions using Mootools. I enjoyed the tutorial so much I thought I would expand upon it and make it a MooTools class that can be reused for various purposes as needed.

Check out the demo.

This class has a couple options you may want to use, position and alignment.

Position can be set to either ‘before’ or ‘after’ which will change whether the caption is above or below the image. Alignment can be set to ‘left’ or ‘right’ or ‘center’ and allows you to align the text within the caption.

If anyone is interested in what the code looks like, here is what you will find in the demo:

/* Let's create a new Class */
var AutoCaptioner = new Class({
	Implements: [Options, Events],

	/* Set up the default options of position: 'after' and alignment: 'center' */
	options: {
					images : [],
					position : 'after',
					alignment : 'center'
	},
	initialize: function(options){
		this.setOptions(options);
		this.addCaptions(this.options.images,this.options.alignment, this.options.position);
	},
	addCaptions : function(images, alignment, position){

		$$(images).each(function(el){			

			var captionText = el.getProperty('title') || el.getProperty('alt');
			if ( captionText ) {
				var figure = new Element('div', {
					'class' : 'figure',
						'styles' : {
							'width' : el.get('width').toInt() + 10
						}
				});
				var caption = new Element('p', {
					'class' : 'caption',
					'html' : captionText
				})
				.addClass(alignment);
				figure.wraps(el);
				caption.inject(el,position);
			} else {
				alert('The image: "'+el.getProperty('src')+'" needs a title or alt value.');
			}
		});
	}
});

window.addEvent('domready', function() {

  /* Let's instantiate a new object */
  new AutoCaptioner({
	  /* set up the options below */
    images : $$('img.captioned'),
		position : 'after',
		alignment : 'center'
	});

});
4 comments so far
  1. Jigga Man says:

    wow… thanks

  2. anonymous says:

    just concern. please visit this site http://feenquegurl.net/ it looks like a heavily edited version of your layout without credits.

  3. Rob Roy says:

    Thanks for this class!

    Once quick fix I think is related to MooTools 1.2 –

    I needed to change the line
    ‘width’ : el.get(‘width’).toInt() + 10
    to
    ‘width’ : el.getStyle(‘width’).toInt() + 10

  4. Just wasting some time on Digg and I found your entry. Not normally what I like to learn about, but it was absolutely worth my time. Thanks.

Thanks for your interest in commenting, but comments are closed on this topic. However, feel free to send me an @reply on twitter.