2

I am trying to calculate the viewport's width, but excluding the scroll-bar's width. Someone on SO said window.innerWidth can do this, but it takes the scroll-bar into account.

I tried using document.body.clientWidth but when the window is horizontally scrolled, this fails.

Even if document.body.clientWidth > window.innerWidth, I need to get the window's width, but without scroll-bar's width

Does anyone have any idea?

Victor
  • 13,914
  • 19
  • 78
  • 147
  • 1
    Have you tried this solution? http://stackoverflow.com/questions/1248081/get-the-browser-viewport-dimensions-with-javascript – Havenard Mar 22 '15 at 21:14
  • It is exactly what I am doing, but more aesthetic – Victor Mar 22 '15 at 21:17
  • @Oriol,it is not duplicate, because there's not what I need. In that question, the OP is not interested in includin/excluding the scroll-bar's width/height, but I am! – Victor Mar 22 '15 at 21:24
  • @Victor Maybe true, but multiple answers address your problem. – Oriol Mar 22 '15 at 21:28
  • Well, the scroll bar is part of the content, so it being taken into accout to the viewport is no mistake. You can try and style the scroll bar so you know exactly what its width is. There are some plugins to help with that, like iScroll.js, NiceScroll etc. that make a neat scroll similar to the iPhone, it hovers over the content and disappears when you are not scrolling or moving your mouse etc. – Havenard Mar 22 '15 at 21:30
  • This one is nice too http://noraesae.github.io/perfect-scrollbar/ – Havenard Mar 22 '15 at 21:38

1 Answers1

3

Using jQuery, $(window).width() will return what you want.

If your document has a horizontal scrollbar, $(document).width() will return the document width instead of the window width.

Using pure JavaScript, you can extract the document width from main window using documentElement with this code which works the same as the jQuery code above:

document.documentElement.clientWidth
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82