Reputation: 26075
The common ways to get the browser's width are all dependent on whether or not <body>
has a scrollbar. For example, window.innerWidth
, document.documentElement.clientWidth
, $(window).width()
, $(window).outerWidth()
, etc all return different results for the following 2 cases:
<html>
<body>
<p>No scrollbar.</p>
</body>
</html>
and
<html>
<body>
<p style="height:10000px">Yes scrollbar.</p>
</body>
</html>
$(window).width()
, etc, all return a higher value for the first case because the scrollbar's width is subtracted for the second case.
How can I reliably get the browser window's actual width regardless of the scrollbar's existence?
Edit: The suggested possible duplicate's answer says to use $(window).width()
while I specifically said $(window).width()
doesn't work.
Upvotes: 2
Views: 556
Reputation: 6264
Please try this
I dont know whether this method is correct or no. But you will get actual width 677 of the sample window
$(document).ready(function(){
$("body").css("overflow", "hidden");
alert($(window).width());
$("body").css("overflow", "auto");
});
You will get the width of the window with the scroll bar as 677 when there is no overflow. Demo for screen width without scroll bar
You will get the width of the window with the scroll bar as 660 when there is overflow. Demo for scree width with scroll bar.
Upvotes: 1
Reputation: 12993
Here is a nice run down of viewport properties from the Quirks Mode site.
The window.innerWidth
is the simplest way of getting this (supported in IE9+ and all other browsers)
// Get the size of the viewport including scrollbars:
var width = window.innerWidth;
console.log('innerWidth=', width);
And here is the MDN documentation on the innerWidth
property.
Upvotes: 1