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:
<img src="mypic.jpg" alt="My picture" width="500" style="width:200px;">- Download this code: /code/be_careful_when_fetching_width1.txt
If you want to fetch the width of that image, like this...
alert(myImage.width);- 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.
Filed under HTML and CSS, Javascript
- ← previous article: Books that made me think
- → next article: Javascript Periodical Executer
Comments:
No comments have been added yet, you could be the first!