Add a “Figure:” label to your Images

We all love documentation, right? I know I would rather be coding or cutting up some images and getting my hands dirty than actually documenting how I did something. It is necessary though, so wouldn't be it great if we had some script help to format our documentation.

Formal documentation often has screenshots and these images should be labelled for referencing. Most of the time, it's enough to just sequentially number the images down the DOM. So, I wrote a script that does this.

So, our script needs to get the index of the image in relation to the document and then display some detail about the image.

Firstly, getting the index of the image is easy. We just loop through all IMG elements in the DOM, and the .each method returns us an index integer.

$("img").each(function (index, value) {
	var imageindex = parseInt(index);
});

Next thing we do is get the image description. We already have this information in the REL attribute of the image (because we are good coders and are very conscious of accessibility). So, as we loop through each IMG element, we will get the REL attribute of the element. We will also check for the existence of the REL attribute, because there are times when an image just doesn't require this attribute.

$("img").each(function (index, value) {
	var imageindex = parseInt(index);
        if ($(this).attr("alt") !== undefined) {
        	// do something here
        }
});

The actual structure of the image label text is completely up to you, but I generally use something like "Figure x: Here is the description". The best way I have found to do this is to build text that is enclosed in an element tag (like a span) and then place it after the image. See this code snippet.

$("img").each(function (index, value) {
	var imageindex = parseInt(index);
        if ($(this).attr("alt") !== undefined) {
            $(this).after("
<div><span class="imagelabel">Figure " + (imageindex + 1) + ": " + $(this).attr("alt") + "</span></div>
"); } });

This code builds up the label text, encloses it in a DIV and then places it after the IMG element in the DOM. Then we add some CSS to style it and we're done.

.imagelabel 
{
    margin: -5px 0px 0px 10px;
    background: #000000;
    color: #ffffff;
    padding: 5px 30px 5px 10px;
}

Til next time ....