Skip to main content

adding captions to images

Providing an 'alt' attribute with an image is generally a good thing. Blogger doesn't ask you to complete the 'alt' attribute of an uploaded image so I rarely provide it as there no real incentive to do so.
By using the 'alt' attribute for a caption there would be a very good incentive.
By putting Jquery to work this can easily be accomplished.

First we have to find the img tags, then we need the value of the alt attribute. I want the caption to be a black box under the image so we have to figure out the width of the image as well.

Finding the img is easy, we only need the images in the posts. All posts are in a div with class 'post-body'. Select them with $('.post-body img').
This gives us multiple images, we walk through the list using 'each()'.
The attribute value is in $(this).attr('alt'), the width of the image can be found with $(this).width.

We can now use this information to compose a variable with the needed content in a div and apply some css.
Finally we append the variable using 'after()'
<script type="text/javascript">
$(document).ready(function() {
$('.post-body img').each(function(){
if ($(this).attr('alt')){


var caption='<div style="width:' + $(this).width() + 'px; text-align:center; padding-bottom:2px; margin-left:auto; margin-right:auto; margin-top:-10px; margin-bottom:10px; background-color:#111111; color:#fff; font-weight:normal; font-size:85%; text-decoration:none;">' + $(this).attr('alt') + '</div>';

$(this).after(caption)} });

});
</script>


When there is no 'alt' value available nothing needs to be done, I added the 'if' condition for that.

screenshot of the script in action

In blogger the editor must be put in html mode the edit the 'alt' atrribute.

Comments