Reputation: 4596
Is it possible to get current distance between left and right? Not full width.
Upvotes: 4
Views: 454
Reputation: 70169
window.innerWidth
can be used to get the browser window viewport width, including scrollbars (if present and rendered).
There's also document.body.clientWidth
which does not include scrollbar, margin, border, or padding - the latter 3 are irrelevant if you have margin:0; padding:0;
and no border set to the body
, which is the case when using a reset stylesheet. Otherwise you just have to compensate for these.
Notes:
clientWidth
, even though being supported by all major browsers (IE 5.5+, FF3+, Chrome, Opera, Safari), has never been defined by W3C so browser support may vary.window.innerWidth
has a W3C spec, but is not supported in IE < 9.Here's a fiddle comparing both.
Edit: window.innerWidth
is not supported in IE<9, so using a mix of innerWidth
and clientWidth
(for older IE) is probably the best approach:
var viewportWidth = window.innerWidth || document.body.clientWidth;
Also, even though clientWidth
is not standardized by the W3C, it is supported in all major browsers so many people find it reliable enough to use solely clientWidth
instead of the W3C standard innerWidth
.
If not including the scrollbar is important for your use-case then clientWidth
can be used as the first/only option:
var viewportWidth = document.body.clientWidth; //no scrollbars included
Ensure that body
has margin:0
and padding:0
in case you use the above.
Upvotes: 4