4

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.
13
  • window.innerWidth should be cross browser (developer.mozilla.org/en-US/docs/Web/API/Window.innerWidth)? That will give you the same width with or without the scrollbar. Commented Dec 6, 2014 at 20:25
  • Like I said the above expression is cross-browser, but it is giving the width with scrollbar. Will window.innerWidth work for IE, Chrome, FireFox, Opera? You are suggesting to just use : var wMax = window.innerWidth? Commented Dec 6, 2014 at 20:28
  • @putvande, Actually I got the cross-browser expression from another post on StackOverflow and the answer did not mention to use only window.innerWidth as a cross-browser solution to getting screen viewport width. Commented Dec 6, 2014 at 20:32
  • The website I linked to says most browsers are supported. Commented Dec 6, 2014 at 20:53
  • 1
    Testing in Chrome, document.documentElement.clientWidth gives the width of the viewport without scrollbar. Commented Dec 6, 2014 at 22:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.