Last Updated: February 25, 2016
·
1.32K
· wallin

Small javascript snippet for adding mobile CSS classes

The following little snippet adds CSS classes to the root HTML element depending on mobile device so you can use conditional styling. It currently adds one or more of the following: ios, android, mobile, webview. The meaning of the names should be self-explanatory

(function(d, l) {
  for (var k in l) {
    if(navigator.userAgent.match(new RegExp(l[k], 'i'))){
      d[k] = true;
      d.documentElement.className+=' '+k;
    }
  }
}(document, {
  ios: '(iPhone|iPod|iPad)',
  android: 'android',
  mobile: 'mobile',
  webview: '(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)'
}));

So for example:

/* ios only styling */
.ios body {
  background-color: #fff;
}

/* android only styling */
.android body {
  background-color: #e7e7e7;
}

it also adds booleans with the corresponding names to the document global so you can use conditional javascript. Ex:

if (document.ios) {
  // Do ios specific stuff
} 
else if (document.android) {
  // Do Android specific stuff
}

1 Response
Add your response

very useful, thank you

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip