jQuery: How to detect window width on the fly?

Dustin picture Dustin · Mar 15, 2012 · Viewed 212.2k times · Source

I have a scrolling element on my page (with the jScrollPane jQuery plugin). What I want to accomplish is a way to turn off the scrolling window by detecting the width of the browser window. I am doing a responsive layout and I want this scrolling feature to be turned off when the browser is below a certain width. I am able to make it work when I refresh the page, but when I resize the browser window the width value does not update on the fly.

Right now if I start out with a window that is 1000px wide then resize to 350px the scroll feature remains. I want the scroll feature to shut off as soon as the browser width hits 440px.

Here's the code I have so far..

var windowsize = $(window).width();

$(window).resize(function() {
  var windowsize = $(window).width();
});

if (windowsize > 440) {
  //if the window is greater than 440px wide then turn on jScrollPane..
    $('#pane1').jScrollPane({
       scrollbarWidth:15, 
       scrollbarMargin:52
    });
}

Answer

Rob W picture Rob W · Mar 15, 2012

Changing a variable doesn't magically execute code within the if-block. Place the common code in a function, then bind the event, and call the function:

$(document).ready(function() {
    // Optimalisation: Store the references outside the event handler:
    var $window = $(window);
    var $pane = $('#pane1');

    function checkWidth() {
        var windowsize = $window.width();
        if (windowsize > 440) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $pane.jScrollPane({
               scrollbarWidth:15, 
               scrollbarMargin:52
            });
        }
    }
    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(checkWidth);
});