Forum Moderators: open

Message Too Old, No Replies

Detecting image attributes in JS

         

Johny Favourite

2:11 pm on Sep 15, 2004 (gmt 0)

10+ Year Member



Is this possible?

What I want is the height and width of it.

Many Thanks.

Bernard Marx

3:15 pm on Sep 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



once you have a reference to the image, eg:


var image document.getElementById("_the_image_id_")
alert(image.width +"\n"+ image.height)

Johny Favourite

3:57 pm on Sep 15, 2004 (gmt 0)

10+ Year Member



Thats wicked sort of.

What I want to do is find out the attritubes of an image that is sat on a server though then once I have the properties I can decide to display it or not.

Is that possible?

Bernard Marx

4:46 pm on Sep 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes. Have an invisible, absolutely positioned image.
Don't use display:none; or it won't work.
Don't give it any dimensions.
[pre]
<img
id="test" style="visibility:hidden;position:absolute;"
onload="getDims_report(this)" onerror="getDims_report(null)">
[/pre]

Then do some thing like this:

[pre]
function getDims_load(src)
{
var img = document.getElementById('test');
}

function getDims_report(img)
{
if(img)
{
if(img.offsetWidth< 200 && img.offsetHeight<200)
alert("display me")
}
/* image not found */
else
..do something else (or not)...
}
[/pre]

whoisgregg

10:12 pm on Sep 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Don't use display:none; or it won't work.

Why not? Does

display:none;
prevent the browser from loading the image at all?

Rambo Tribble

10:36 pm on Sep 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, display:none suppresses loading.

I believe you can also do this server-side with PHP, without necessarily having to download the image.

Bernard Marx

7:03 am on Sep 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I didn't know display:none; did that, to be honest.
My thinking was that an element doesn't have valid offset properties until display is on.

Johny Favourite

7:52 am on Sep 16, 2004 (gmt 0)

10+ Year Member



I have been trying to work that out on and off for weeks, thanks guys!

:D