Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reliably get screen width WITH the scrollbar

Is there a way to reliably tell a browser's viewport width that includes the scrollbar, but not the rest of browser window)?

None of the properties listed here tell me the width of the screen INCLUDING the scrollbar (if present)

like image 950
Goro Avatar asked Nov 17 '11 02:11

Goro


People also ask

How can I get scrollbar width?

To get the width of the scrollbar, you use the offsetWidth and clientWidth of the Element : The offsetWidth returns the width of the Element in pixels including the scrollbar. The clientWidth returns the with of the Element in pixels without the scrollbar.

Does viewport width include scrollbar?

Many assume that width: 100vw is the same as width: 100% . This is true on a page that doesn't scroll vertically, but what you might not realize is that the viewport actually includes the scrollbars, too.

How do I know my screen width?

Use window. innerWidth and window. innerHeight to get the current screen size of a page.

How many pixels wide is a scroll bar?

The default scrollbar width can range anywhere from 12px to 17px. Webkit browsers also have the ability for the user to configure scrollbar widths. Webkit browsers, such as Chrome can have custom scrollbars that can have any size scrollbar.


1 Answers

I figured out how to accurately get the viewport width WITH the scrollbar using some code from: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript

Put this inside your $(document).ready(function()

$(document).ready(function(){
    $(window).on("resize", function(){
      function viewport() {
          var e = window, a = 'inner';
          if (!('innerWidth' in window )) {
              a = 'client';
              e = document.documentElement || document.body;
          }
          return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
      }
    });
    // Get the correct window sizes with these declarations
    windowHeight = viewport().height;
    windowWidth = viewport().width;  
});

What it Does:

When your page is 'ready' or is resized, the function calculates the correct window height and width (including scrollbar).

like image 86
Joshua Plicque Avatar answered Oct 03 '22 22:10

Joshua Plicque