Last Updated: February 25, 2016
·
390
· alexlafroscia

Javascript Variable for Page Width

Sometimes, especially with jQuery, you want to be able to have certain actions execute only when the page width is above or below some breakpoint (this is especially helpful with the advent of RWD). A good way to do with is to set a page width variable, like this (this is all jQuery, by the way):

pageWidth = $(window).width();

This is fine and good – if you're not changing the size of the browser. However, this only gets set when a page gets loaded. Once the page width changes, however, it is no longer accurate. A better set to take would be this:

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

This tells the variable to constantly be re-set to the current width of the page, whenever with width changes, as well as getting the current width when the page loads.

However, one problem remains – that variable gets stuck within the function. So, the complete, best version would be something like this:

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

This creates an object called thePage, and then the two functions set the property width to the width of the page. Now, you can always refer to thePage.width in another function, and you never have to worry about problems with setting global variable.