Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clientWidth and clientHeight always returns zero for ie7

I have no idea why, but clientWidth and clientHeight are always returning zero when I run this from IE in IE9 compat View, or IE7. It works for everything else. Very simple code snippet with problem (so that you can try it too): http://jsfiddle.net/nz2DA/

The code snippet found above is as follows... I have a page containing the following HTML snippet:

<div id='aaa'>aaaaaa</div>​

And my javascript to test the clientWidth and clientHeight functions are as follows:

var el = $('#aaa')[0];
alert('Client width and height: '+ el.clientWidth + ' X ' + el.clientHeight);​

This always pops up an alert with "0 X 0" when I run in IE7 or IE9 Compatibility mode.

Any help or explanation would really be appreciated. Thanks!

like image 395
Mark Whitfeld Avatar asked Apr 15 '26 18:04

Mark Whitfeld


1 Answers

This is happening because of the "hasLayout" property in IE, and your div on its own does not "have layout". For more information, see http://www.satzansatz.de/cssd/onhavinglayout.html

Luckily you can trigger an element to have layout, which is why adding the "float:left" style works in the answer above. There are other triggers you can use too though that don't change the page. This one gives me proper values for clientWidth and clientHeight:

<div id="aaa" style="zoom: 1">aaaaaa</div>

The article says that setting "min-width: 0" should also work but it didn't for me. Setting "display: inline-block" worked OK but that might change your page. You can set these triggers in CSS so that the HTML doesn't need to change at all.

like image 161
foz Avatar answered Apr 17 '26 06:04

foz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!