Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery window width sometimes return wrong value

SOMETIMES when I call:

$(window).width();

the value returned is wrong (on all browsers except IE, on IE it is always correct). I use the line:

$('div.container p').text($(window).width());

to change the text of the p element so I could see what value was returned when I am resizing the window. Here is an example when the value returned is wrong: http://prntscr.com/7biu4y

In the top right corner, you can see what the actual dimensions are on Chrome.

I noticed that WHEN the value is wrong, it is always off by 17px.

NOTE that the value returned is NOT always wrong so most of the times the window looks as it should.

Help!

like image 947
user435421 Avatar asked May 31 '15 16:05

user435421


2 Answers

@Inacio Schweller is correct.

To get a consistent cross-browser result, you can use the non-jQuery version:

window.innerWidth

Try typing this into the console of your browser and you'll see that it returns a consistent result regardless of the browser you are using.

Note: The non-jQuery version window.outerWidth returns the same result in IE and Chrome, but returns a slightly smaller value in Firefox.

like image 171
trevor Avatar answered Nov 17 '22 06:11

trevor


It's because of the scrollbar of the browser's viewport. If you minimize the window enought to show the scrollbar, the viewport will say it's 17px smaller than your value. If the window is full, the 17px difference will not appear.

like image 5
Inacio Schweller Avatar answered Nov 17 '22 07:11

Inacio Schweller