Leo Jiang Leo Jiang - 4 months ago 8
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;
setInterval(function(){
if($(window).width()!=prev)
console.log(prev=$(window).width());
},1);


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
$(window).width()
change without resizing the window? Shouldn't it return the browser window's width, which should be constant?

Answer

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