Sunil
Sunil

Reputation: 21406

Cannot get width of screen without scrollbar using cross-browser expression

I am using the following expression in JavaScript to get the width of screen, which seems to work fine except that it includes the width of vertical scroll-bar when scrolling is there.

var wMax = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)

Question: How can the above cross-browser expression be modified so it gives the width of screen excluding the vertical scrollbar? I need to use JavaScript for this and not jQuery.

UPDATE 1:

I found the following cross-browser expression to give the width excluding the vertical scroll-bar.

var wMax = Math.min(document.documentElement.clientWidth, window.innerWidth 
                      || screen.width);
  1. I used Math.min rather than Math.max, so that whichever width was less was taken for width
  2. and also used screen.width instead of 0 in the original expression since screen.width would always be maximum of all widths in this case for all browsers as it will always include scroll-bars.

Upvotes: 4

Views: 933

Answers (1)

Rodrigo5244
Rodrigo5244

Reputation: 5535

screen.width is the width of the display screen, not the window of the browser excluding the scroll bar.

You should use Math.min instead of Math.max since the width without the scroll bar is going to be smaller than the width with scroll bars.

Also if there is a browser that does not work properly, you could try getting the width of the body or html tag without clientWidth like this document.documentElement.scrollWidth.

Upvotes: 1

Related Questions