Be careful when fetching width!

Posted on 26 July 2007 (12:04 AM)

I stumbled across a little oddity today. It kept me busy for longer than I would've liked, so I thought I'd share (although you're probably not very likely to run into the problem, since it's not a very common situation).

Consider this little bit of code:

  1. <img src="mypic.jpg" alt="My picture" width="500" style="width:200px;">
  2. Download this code: /code/be_careful_when_fetching_width1.txt

If you want to fetch the width of that image, like this...

  1. alert(myImage.width);
  2. Download this code: /code/be_careful_when_fetching_width2.txt

...it will actually give you the width as declared in the CSS rule, e.g. the rendered width! It makes sense, as this is the actual rendered width, but it can really be a pain in the butt when you're trying to access the width attribute instead of the rendered width. View the source of this example for some proof.

As I said; you're probably not likely to run into the problem, but it's good to know about it. You never know.

It can be easily worked around by the way, by using the W3C standard method getAttribute.

Back to top

Filed under HTML and CSS, Javascript

Comments:

No comments have been added yet, you could be the first!

Leave a comment

RE: Be careful when fetching width!

Note to spammers: rel="nofollow" will be added to links. If I consider your comment spam, your IP-address might get blocked.

HTML not allowed. URLS will be auto-linked. Maximum length is 1250 characters.

I understand this is inconvenient, but the spam I'm receiving on this website is driving me nuts. Please forgive me and cope with it until I find a better solution.

Mandatory fields are marked by an asterisk (*).

Increase textarea-size Decrease textarea-size

Back to top

Preferences

These settings will be saved for your convenience.