Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to detect window width on the fly?

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     }); } 
like image 359
Dustin Avatar asked Mar 15 '12 13:03

Dustin


People also ask

How do you measure window width?

You can also get the WINDOW width and height, avoiding browser toolbars and other stuff. It is the real usable area in browser's window. To do this, use: window. innerWidth and window.

What is the meaning of $( window width ()?

$(window). width() gets the entire width of the window, including things like the scroll bar .

How do I find the width of my HTML screen?

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


2 Answers

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); }); 
like image 144
Rob W Avatar answered Oct 14 '22 04:10

Rob W


Put your if condition inside resize function:

var windowsize = $(window).width();  $(window).resize(function() {   windowsize = $(window).width();   if (windowsize > 440) {     //if the window is greater than 440px wide then turn on jScrollPane..       $('#pane1').jScrollPane({          scrollbarWidth:15,           scrollbarMargin:52       });   } }); 
like image 26
antyrat Avatar answered Oct 14 '22 04:10

antyrat