Tuesday, April 10, 2012

Detecting Browser Display Width Using Jquery - Responsive Design

I have recently been working on a project that needs to be 'responsive' dependent on the visible browser area, I have written some Jquery code that detects the user's browser display width and disables or enables stylesheets as required, I have included a snippet below should this help anyone.

function ProcessPageSize() {

//Configure stylesheets based on visible area.

setStyleEnabled("deskStyle", true);
setStyleEnabled("deskStyle2", true);
setStyleEnabled("handheldStyle", false);
setStyleEnabled("tabletStyle", false);

//get window width
var width = $(window).width();

if (width < 960) {
setStyleEnabled("deskStyle", false);
setStyleEnabled("deskStyle2", false);

if (width < 400)
setStyleEnabled("handheldStyle", true);
else
setStyleEnabled("tabletStyle", true);
}

}

function setStyleEnabled(styleName, isEnabled)
{
$('link[@rel*=style][title]').each(function (i) {
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = !isEnabled;
});
}

//Call configure page function
$(document).ready(function () {
ProcessPageSize();

$(window).resize(function () {
//resize just happened, pixels changed
ProcessPageSize();
});



});

See a jpr freelance - built responsive design in action - here