...

View Full Version : jquery: an error fromcreating image caption from alt



lauthiamkok
09-23-2009, 12:35 AM
Hi,

I made this code to create image caption from the alt sometime ago. But recently I notice there is a bug or an error.

The width of the div of the image caption should be following the width of the individual image. It picks up the width of each images successfully. But it only take the width of the last image when the code has ran completely.

This is the html code,


<div id="content">

<p><img src="bw1.jpg" alt="Ut wisi enim ad minim veniam" width="300" /></p>
<p><img src="bw2.jpg" alt="pic 2" width="550"/></p>
<p><img src="lights1.jpg" alt="pic 3" width="500"/></p>

</div>

this is the jquery,


$(document).ready(function(){

$("#content img").each(function () {
var imgwidth = $(this).width();
var title = $(this).attr("title");
var alt = $(this).attr("alt");
alert(imgwidth);

$("<div class='image_description'>"+"<span class='image_title'>"+ title +"</span>"+"<span class='image_alt'>"+ alt +"</span>"+"</div>").insertAfter(this);
$('.image_description').css({
color: '#666666',
fontSize: '11px',
margin: '0px 0px 0px 0px',
clear: 'both',
width: imgwidth
});

$('.image_title').css({
fontStyle: 'italic'
});

});

});

this is the live link,

http://lauthiamkok.net/tmp/jquery/jquery.image_caption/

Many thanks if u know why...

Thanks,
Lau

Spudhead
09-24-2009, 02:53 PM
Hmm. Something very strange is going on with jQuery's width() function. In my FF3.5, it's returning 675 for that top image, and 26 for the other two. I'm not sure what's happening here.

However, css("width") does return the correct value. And with the added bonus that it's got the "px" on the end - you don't have this when you use the width to set the CSS of the image_description div, and I think that may have caused you problems.

Anyhow, using the css width seems to sort it out.

lauthiamkok
09-24-2009, 06:49 PM
Hmm. Something very strange is going on with jQuery's width() function. In my FF3.5, it's returning 675 for that top image, and 26 for the other two. I'm not sure what's happening here.

However, css("width") does return the correct value. And with the added bonus that it's got the "px" on the end - you don't have this when you use the width to set the CSS of the image_description div, and I think that may have caused you problems.

Anyhow, using the css width seems to sort it out.

hey thanks i have fixed it - just need to chain the function like this,


$("<div class='image_description'>"+"<span class='image_title'>"+ title +"</span>"+"<span class='image_alt'>"+ alt +"</span>"+"</div>").insertAfter(this).css({
color: '#666666',
fontSize: '11px',
margin: '0px 0px 0px 0px',
clear: 'both',
width: imgwidth
});

:D



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum