Robert C.
Robert C.

Reputation: 15

Creating image caption from alt script

I am trying to use this jQuery script to make an image caption from the alt tag:

$("#content img").each(function () {
    var $this = $(this);
    var title = $this.attr("alt");
$this.after('<div class="caption">'+ title +'</div>');
});

I am using another jQuery script before it and it is working fine. I can't seem to get the caption to alt script to work.

Example: www.cslack.com/test.html

Thanks,

Robert

Upvotes: 0

Views: 3098

Answers (3)

CodeJoust
CodeJoust

Reputation: 3790

 $(function(){

   $('a > img[style]').each(function(){
       $el = $(this);
       var style = $el.attr('style');
       $el.attr('style','');
       $el.parent().attr('style',style);
    }); //Moves the inline styles

      $("img").each(function(){
          var title = this.alt;
          $(this).after('<div class="caption">'+ title +'</div>');
      }); //Adds the dynamic captions.
 }); 

Upvotes: 1

SLaks
SLaks

Reputation: 887405

Your problem is that you're executing your code before the images exist.

You need to wrap the code in $(function() { code }) to make it run after the document loads.

Alternatively, you can move the <script> block to the end of the <body> tag after the img tags.

Also, your HTML doesn't have a #content element; you need to either change the selector to img or put all of the <img> tags inside a <div id='content'>.

Upvotes: 3

Dumb Guy
Dumb Guy

Reputation: 3446

On your example page, there is no such thing as #content which is why it doesn't work.

If you place a <div id="content"> around your content, then it should work.

Upvotes: 1

Related Questions