Convert ALT to Caption

R

Roy Reed

I found a script that converts image alt text to a caption which I've tried
to modify for my needs:

function addCaption(imgElem) {
var captionElem = document.createElement("div");
captionElem.className = "caption";
var captionText = document.createTextNode(imgElem.alt);
captionElem.appendChild(captionText);
if(imgElem.nextSibling)
imgElem.parentNode.insertBefore(captionElem,imgElem.nextSibling);
else
imgElem.parentNode.appendChild(captionElem);
with(imgElem.style) {
captionElem.style.width =
(imgElem.width+borderLeftWidth+borderRightWidth+paddingLeft+paddingRight)+"px";
}
return true;
}

<img src="forest.jpg" width="515" height="183" alt="Strathyre Forest at
Dawn - the forest is bathed in golden light and mist rises from between the
trees - &copy; Roy Reed, 1987" onload="javascript:addCaption(this)">

This works as I want if no border or padding is added to the image, but not
if they are. In IE6 the padding is added to the width of the created div,
but not the border width. In Firefox nothing is added.
Can anyone tell me how this should be coded.

Live example (with attribution to original code) at
www.reeddesign.co.uk/autocaption/

Thanks

Roy Reed
 
M

marss

Roy Reed напиÑав:
with(imgElem.style) {
captionElem.style.width =
(imgElem.width+borderLeftWidth+borderRightWidth+paddingLeft+paddingRight)+"px";
}

You add string values.

<img width="500px"style="padding: 5 5 5 5">
In this case instead of "510px" you will get "500px5px5pxpx"
Use parseInt or parseFloat before summation.
 
R

Roy Reed

Roy Reed ???????:
You add string values.

<img width="500px"style="padding: 5 5 5 5">
In this case instead of "510px" you will get "500px5px5pxpx"
Use parseInt or parseFloat before summation.

Is this what you meant?

with(imgElem.style) {
captionElem.style.width = parseFloat(imgElem.width+borderLeftWidth+
borderRightWidth+paddingLeft+paddingRight)+"px";
}

It gives exactly the same result.

Thanks for trying to help with this. I'm not a JavaScript expert.

Roy
 
M

marss

Roy Reed напиÑав:
Is this what you meant?

with(imgElem.style) {
captionElem.style.width = parseFloat(imgElem.width+borderLeftWidth+
borderRightWidth+paddingLeft+paddingRight)+"px";
}

No. I mean something like this
with(imgElem.style) {
captionElem.style.width =
(parseFloat(imgElem.width)+parseFloat(borderLeftWidth)+

parseFloat(borderRightWidth)+parseFloat(paddingLeft)+parseFloat(paddingRight))+"px";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top