Leo Jiang Leo Jiang - 1 year ago 57
Javascript Question

Why does $(window).width() change while the page is loading?

I noticed that my scripts were setting widths incorrectly, so I tried the following snippet:

var prev;

This printed 2 different values: 1464 and 1481. Since these are 17px apart, I'm almost certain this is caused by scrollbars. The second value is the correct value.

Why does
change without resizing the window? Shouldn't it return the browser window's width, which should be constant?

Answer Source

$(window).width() is affected by the margin, border and padding. These can change as the DOM is being loaded. As mentioned above, make sure you are waiting until $(document).ready() before you start looking at / twiddling with the DOM objects.

More info here http://api.jquery.com/width/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download