dedavarera
dedavarera

Reputation: 53

Why does offsetWidth show incorrect value?

I wrote this code.

When I added scroll-bar, I got 403 as clientWidth, and this seems like true: 403px for inner content + 17px for scroll-bar. And then I got 403 as offsetWidth, but offsetWidth must include scroll-bar width. Therefore I should get 403+17, not 403.

Why do I get 403 as result in (*)?

let html = document.documentElement
console.log(window.innerWidth) // 420 on my test
console.log(html.clientWidth) // 420
console.log(html.offsetWidth) // 420

html.style.overflowY = 'scroll' // add scroll-bar
console.log('Window: ' + window.innerWidth) // Window: 420
console.log('clientWidth: ' + html.clientWidth) // clientWidth: 403
console.log('offsetWidth: ' + html.offsetWidth) // offsetWidth: 403 (*)

Upvotes: 3

Views: 1030

Answers (1)

You almost got us! But there it is...

Take a closer look at the documentElement.

Layout of documentElement

The scrollbar is not included! Therefore the only way to get the site width including scrollbars is window.innerWidth.

The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.

The value of offsetWidth will include scrollbars for all elements except the documentElement.
offsetWidth of documentElement includes scrollbars, but it simply doesn't have any. Which means that offsetWidth and clientWidth are the same.

Upvotes: 2

Related Questions