Posted By

vaughanj on 04/06/13


Tagged

image alt caption


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

imoddesign
atulkransingh


Use jQuery to display an image alt tag as a caption overlay


 / Published in: jQuery
 

URL: http://davemcmillan.net/447/snippets/use-jquery-to-display-an-image-alt-tag-as-a-caption-overlay/

Loop through all the images in a given container, grab their alt tags if they are not empty, and then create an overlay in a span tag that will be positioned on the bottom corner of the each image.

  1. // display image caption on top of image
  2. $("#content img").each(function() {
  3. var imageCaption = $(this).attr("alt");
  4.  
  5. if (imageCaption != '') {
  6. var imgWidth = $(this).width();
  7. var imgHeight = $(this).height();
  8. var position = $(this).position();
  9. var positionTop = (position.top + imgHeight - 26)
  10. $("<span class='img-caption'><em>"+imageCaption+"</em></span>")
  11. .css({"position":"absolute", "top":positionTop+"px", "left":"0", "width":imgWidth +"px"})
  12. .insertAfter(this);
  13. }
  14.  
  15. });

Report this snippet  

You need to login to post a comment.