0

I am messing around with some code and applying / removing classes based on window size and I'm running into a weird error. I've confirmed that I'm at the default zoom (if that matters), and I've replicated the issue in FF & Chrome.

I have a resize event handler that I'm just using to monitor the javascript window width value vs. the actual value (I have a chrome extension which shows the window & viewport width as you're resizing, and my bootstrap viewports hit exactly as they should at 992px, 1200px etc, so I know that the javascripts value is off for some reason and not vice-versa)

For some reason, as I resize the window, the value for window width that shows in the console.log, is always 21px smaller than the actual screen size. This is the code that I'm using for the test:

var w = 0;
    $(function () {
        w = $(window).innerWidth() || $(window).width();
    })
    
    $(window).resize(function () {
        if (w != $(window).innerWidth()) {
            w = $(window).innerWidth() || $(window).width();
            console.log(w);
        }
    });
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
user3267755
  • 1,010
  • 1
  • 13
  • 32
  • Is it because you have dev tools open, making the screen shorter? – tcigrand Sep 17 '15 at 17:33
  • I keep dev tools in a separate window on my other screen – user3267755 Sep 17 '15 at 17:34
  • 6
    21px smaller - scrollbar width, maybe? – sinisake Sep 17 '15 at 17:35
  • I'm thinking that's it. I just took a ruler extension from chrome and it won't let me select the scrollbar, so I did the whole width of the rest of the page and it matched exactly what javascript is recording for the width..is there a reason that JavaScript wouldn't include the scrollbar inherently? – user3267755 Sep 17 '15 at 17:40

1 Answers1

1

Give this a try:

var iw = $('body').innerWidth();

jsBin demo

answer from: https://stackoverflow.com/a/8340177/504836

Community
  • 1
  • 1
joelnet
  • 13,621
  • 5
  • 35
  • 49
  • I added your snippet out of curiosity to my `console.log` and it's recording the same answer as the variable `w` which is window width. - w 883 (index):404 body 883 (index):403 w 880 (index):404 body 880 (index):403 w 879 (index):404 body 879 – user3267755 Sep 17 '15 at 17:43
  • You might have to set the body margin to 0 for this to work. – joelnet Sep 17 '15 at 17:48
  • I just checked the inspector out of curiosity and this was the rule : body { margin: 0; } – user3267755 Sep 17 '15 at 17:54