views:

106

answers:

3

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

+1  A: 

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.

Dumb Guy
+1 for the quick find, alternatively (and probably a slightly better solution in this case) you could just remove the #content and just leave $("img") which will select each img on the page.
Jay
A: 
 $(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.
 });
CodeJoust
No, don't use `append` instead of `after`. Calling `append` will put the `div` _inside_ the `<img>` tag, which is not what he wants.
SLaks
Thanks. Next time, I'll look at the demo page...
CodeJoust
Thank you guys for your help. I still am not quite able to get it working. I am pretty new to this. Would you mind taking another look?
Robert C.
It looks find. Doing what is advertised!OK-- your javascript is fine (although it's a good idea to only include jQuery once in the page).However, your problem lies within the css styling of each image.I'd move the style="position..." to the <a name=""> element instead of the <img src=... element it's on now, then the captions will be moved along with the images.
CodeJoust
Works great, thank you so much.
Robert C.
+3  A: 

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'>.

SLaks