Responsive Design Opt-Out

Sometimes you just want to view a website as it would appear on a desktop, the problem is, with responsive design, user agent queries are ignored and the site will re-size itself despite clicking the “View Desktop Version” option in your mobile browser.

For the development of williamssound.com, I made it responsive using the typical combination of Media Queries and JavaScript but also wanted a way for a user to “opt-out” as it were.

The solution involves a bit of JavaScript and setting a cookie.

Since a key component of the responsive design is in the “meta” tag, I needed to actually write that into the <HEAD> upon page load. In addition, I have a separate CSS file that contains all the definitions for my media queries for the responsive stuff. This allows me to only load that style sheet when I want/need it.

So, inside the <HEAD> area, I insert the following:

<script type="text/javascript">
  if ($.cookie('disableResponsive') !== '1') {
    document.write('<link rel="stylesheet" type="text/css" href="/css/responsive.css" media="screen" />');
    document.write('<meta id="mobileviewport" name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width" />');
  }
</script>

All this does is check to see if a particular cookie has been set, and if not, write the responsive code to the HTML. By not including it, I have effectively turned my responsive site into a static one.

Somewhere on the site (it’s in the footer on williamssound.com) I create a hashed link with the ID “disableResponsive”. In my scripts file for the site, I have the following code:

$('a#disableResponsive').click(function () {
  if ($.cookie('ws_disableResponsive') != '1') {
    $.cookie('ws_disableResponsive', '1', {expires: 14});
    alert('Mobile website functionality disabled. Click again to re-enable.');
    window.location.reload(true);
  } else {
    $.cookie('ws_disableResponsive', '0', {});
    alert('Mobile website functionality enabled.');
    window.location.reload(true);
  }
  return false;
});

This will toggle the cookie and turn the responsive design off and on as the user requests.

My next step is to integrate User Agent override detection into it so it will also work if someone checks the “Request Desktop Version” option on their mobile browser. I’ll update this post when I have that working.