Wednesday, April 1, 2009

[jQuery] Re: Using the title attribute if images as captions

In the first version, you're wrapping the img with a div, then trying
to ad the caption to a child div of the img. There was also a typo
(cright instead of cleft).

In the 2nd version, you're trying to append the caption to *all* divs
with classname captionwrap.

Try this:

$(function (){
$('img.cright, img.cleft').load(makeImgCaption);
});

function makeImgCaption()
{
$('<div/>').addClass('Caption')
.css('width', $(this).width())
.html($(this).attr('title'))
.insertAfter($(this));
}


On Wed, Apr 1, 2009 at 8:28 AM, osu <onesizeup@googlemail.com> wrote:
>
> As a development on this thread, I've changed my code to the following
> based on someone else's comments, but I still can't get it to work (by
> the way, the $j is in there as part of a method to avoid conflict with
> Joomla's Mootools library - I'm building this site in Joomla).
>
> Any ideas of what I'm doing wrong? The caption isn't appearing?
>
> Thanks,
>
> osu
>
> // Create caption from title attribute for images with
> class="imgcaption"
>        $j('img.cright').each(function(){
>                var caption = '<p>' + $j(this).attr('title') + '</p>';
>                $j('img.cright').wrap('<div class="captionwrap"></div>');
>                $j('div.captionwrap').append(caption);
>        });
>
>        $j('img.cleft').each(function(){
>                var caption = '<p>' + $j(this).attr('title') + '</p>';
>                $j('img.cleft').wrap('<div class="captionwrap"></div>');
>                $j('div.captionwrap').append(caption);
>        });
>
>
> On Apr 1, 1:36 pm, osu <onesiz...@googlemail.com> wrote:
>> Hi,
>>
>> I'm trying to use the title attribute of images to create a simple
>> caption below the image. To do so, I've been trying to wrap the image
>> (floated left or right) in a div and add a caption that's taken from
>> the image attribute.
>>
>> So far, I have:
>>
>> Code:
>> // Create caption from title attribute for images with
>> class="imgcaption"
>>    $j(function(){
>>       var caption = $j('img').attr('title');
>>       $j('img.cright').wrap('<div></div>');
>>       $j('img.cright div').append(caption);
>>    });
>>
>>    $j(function(){
>>       var caption = $j('img').attr('title');
>>       $j('img.cleft').wrap('<div></div>');
>>       $j('img.cright div').append(caption);
>>    });
>>
>> But this isn't working. Can anyone see what the problem is? When I
>> change the variable to:
>>
>> Code:
>> var caption = $j(this).attr('title');
>>
>> It just uses the title attribute of the HTML document. Ideally, I'd
>> like to wrap the caption in a <span> tag as well, but don't know how
>> to do that.
>>
>> Any ideas greatly appreciated.
>>
>> Thanks
>>
>> osu

No comments: