Search code examples
javascriptjquerycsswindowmedia-queries

Calculate window width including scrollbar - CSS Media queries vs. JS


Assuming I've deduced the problem correctly, it seems that the CSS min-screen width compensates for a scrollbar (as would be expected), while JS doesn't seem to do the same :(

I'm using Firefox on Mac OSX. I'm not sure if this is browser specific, but I'm wondering if there's a universal solution to this problem.

I've made a JS fiddle to demonstrate the problem. In my browser, there's is a 15px difference between the width calculated by the CSS and my JS.

Anyone encountered this before?


Solution

  • I seem to have found an answer to my question, though I'm not sure if this is the most efficient way to calculate the correct width.

    The idea is to give the body element overflow:hidden;, then run the function to calculate the window width, then remove the overflow:hidden; style.

    Like so:

    function minScreen480(){
    
        document.body.style.overflow = "hidden";
            if ($(window).width() >= 480) {
                // Do stuff
            }else{
                // Do stuff
            }
        document.body.style.overflow = "";
    }
    
    $(window).resize(function(){
        minScreen480();
    }).trigger('resize');
    

    Seems to work. Could this written better?