getting width of a replaced image?

E

erikv

I'm having a hard time figuring out how to get the width of an image I
replace using the following code:

document.getElementById("sizeImg").src="http://www.example.com/image.jpg";

After this code, I try to snag the width of the new image using this:

document.getElementById("sizeImg").width

But I don't get the results I'm after in Firefox or IE. Firefox is
always one behind, meaning every time the image is replaced, the value
I get is the width of the previous image. IE always displays the
value as 0.

I've tried preloading the image after replacing it. I've tried a few
other things I found in this newsgroup, too. But I can't seem to get
the width of the image.

Does anyone know what I can do? I'd prefer it to work in Moz as well
as IE.

Thanks,
Erik
 
M

Martin Honnen

erikv said:
I'm having a hard time figuring out how to get the width of an image I
replace using the following code:

document.getElementById("sizeImg").src="http://www.example.com/image.jpg";

After this code, I try to snag the width of the new image using this:

document.getElementById("sizeImg").width

But I don't get the results I'm after in Firefox or IE. Firefox is
always one behind, meaning every time the image is replaced, the value
I get is the width of the previous image. IE always displays the
value as 0.

The browser needs to load the image before it can tell you its
dimensions thus you have to use the onload handler to check the width:
<img name="imageName" src="whatever.gif" alt="what ever">
then
var img = document.images.imageName;
img.onload = function (evt) {
alert('Current dimensions: ' + this.width + 'x' + this.height);
};
img.src = 'whatelse.gif';
img.alt = 'what else';
 
E

erikv

Thanks, Martin.

The issue is now resolved. For everyone else's benefit, my solution
was to use Martins code below, putting the conditional code that
checks against the new image dimensions in the function (evt) block.

I'd been trying all kinds of tricks with settimeout and onload, but
nothing worked until this.

-Erik
 

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
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top