Allowing mobile users to toggle between desktop and mobile versions

While responsive site stylesheets that give mobile users an alternate small-screen version of your site are a good idea, not every mobile user wants the small-screen version. Fortunately, it’s possible to give them a choice in the matter using only a little bit of JavaScript.

Here’s one approach that takes advantage of mobile browsers’ use of the <meta name="viewport" content="width=device-width"> tag.

If the <meta name="viewport" content="width=device-width"> tag is not present, mobile browsers should display the desktop version of the page instead. We can set up a little bit of JavaScript to write out this tag only if a certain cookie is set (as close to the top of the <head> section as possible):

var dv = readCookie('desktopview'); // or some other unique name
if (dv != "1") { // cookies are always stored as strings
  document.write('<meta name="viewport" content="width=device-width">');
}

You probably wondered about that readCookie function. Unfortunately, JavaScript doesn’t parse the browser cookie automatically, so we include a bit of code to do that first, borrowed in whole from http://www.quirksmode.org/js/cookies.html:

function createCookie(name,value,days) {
  if (days) {
  var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

Now we add a function to toggle the cookie value between zero and one, and then reload the page:

function toggleViewport() {
  createCookie('desktopview',1-(dv||0),0); 
      // 'dv' is implicitly converted to a number 
  window.location.reload();
}

Finally, at the top of our document, we need to add a link which can be used to switch to the desktop view:

 <a href="javascript:toggleViewport()">Desktop version</a>

To hide this link from desktop browsers, we can add a class to it and set display:none for wider browser windows. This will also prevent our mobile users from switching back to the mobile version, alas. But if they quit their browser completely and return to our site later, the cookie will be forgotten and the mobile version will once again be presented by default.

Leave a Reply

Your email address will not be published. Required fields are marked *

*