Leo Jiang Leo Jiang - 3 months ago 6x
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?


$(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/