Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.innerWidth includes the scroll-bar width [duplicate]

Tags:

javascript

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?

like image 229
Victor Avatar asked Feb 15 '26 16:02

Victor


1 Answers

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
like image 156
Ali Sheikhpour Avatar answered Feb 17 '26 04:02

Ali Sheikhpour