Hi g8z,
The problem you're probably running into is that Netscape doesn't
"know" the width and height of the image right away; it has to wait a
small amount of time for the image to be loaded. IE doesn't have this
problem. For instance, with the following code (where "pic.gif" is in
the browser cache), IE gives the correct answer twice, whereas
Netscape prints zero the first time and the correct width the second
time:
Image img = new Image();
img.src = "pic.gif";
alert (img.width);
setTimeout ("alert (img.width)", 1);
A robust solution to your problem, then, is to wait until the sizes
are available by repeatedly calling setTimeout. Here's code for a
routine, called runWhenSizeAvailable, that does that for you:
MAX_TRIES = 300; // number of times to check for the image size
before giving up
SLEEP_TIME = 50; // number of milliseconds to sleep between size
checks
function escapeQuotes (str) {
return str.replace (/'/g, "\\'")
}
function checkSize (imgstr, code, triesRemaining) {
eval ("img = " + imgstr);
if (img.width != 0 && img.height != 0) { // IE doesn't do
img.complete
paren = code.lastIndexOf (")");
code = paren == -1 ? code + "(img.width,img.height)" :
code.slice (0, p\
aren) + ",img.width,img.height)";
eval (code);
} else if (triesRemaining > 0) {
setTimeout ("checkSize('" + escapeQuots (img) + "', '" +
escapeQuotes (\
code) + "', '" + (triesRemaining - 1) + ")", SLEEP_TIME);
}
}
/* Takes a string reference to an image and a string of the name of
a
* user function (optionally with arguments) to run when the image's
size
* is available.
*
* Example:
* runWhenSizeAvailable ("document.images[0]", "myFunc (44,
'hi')");
* When the size of the first image in the document is available,
the
* function "myFunc" will be called automatically as follows:
* myFunc (44, 'hi', width, height);
* where width and height are the dimensions of the image. Note that
myFunc
* is a four-argument function; the last two arguments are not
specified in
* the "code" string when calling runWhenSizeAvailable, as they are
filled in
* by runWhenSizeAvailable.
*/
function runWhenSizeAvailable (img, code) {
checkSize (img, code, MAX_TRIES);
}
Use the above routine like this:
function printSize (msg, width, height) {
alert (msg + ": " + width + "x" + height);
}
for ( j = 1; j < n; j++ )
{
document.write("<img width=60 height=42 id=img" + j + " name=img"
+ j + " src=../images/image_" + j + ".jpg>" );
runWhenSizeAvailable ("document.images['img" + j + "']",
"printSize ('size of image " + j + " is ')");
}
I have confirmed that this works on IE 5+ and NS 6+.
cheers,
dogbite-ga |