Skip to content

Instantly share code, notes, and snippets.

@KruegerDesigns
Created April 24, 2012 16:45
Show Gist options
  • Save KruegerDesigns/2481363 to your computer and use it in GitHub Desktop.
Save KruegerDesigns/2481363 to your computer and use it in GitHub Desktop.
Android, iOS detection, then adds a class to the HTML tag.
// adds mobile browser class to html tag
var ua = navigator.userAgent.toLowerCase();
function removeSpaces(ua) {
return ua.split(' ').join('');
}
ua = removeSpaces(ua);
var iOS = ua.match(/(iphone|ipod|ipad)/);
if(iOS) {
$('html').addClass('ios');
}
var iPad = ua.match(/(ipad)/);
if(iPad) {
$('html').addClass('ipad');
}
var iPhone = ua.match(/(iphone|ipod)/);
if(iPhone) {
$('html').addClass('iphone');
}
var android = ua.indexOf("android") > -1;
if(android) {
$('html').addClass('android');
}
var android4 = ua.indexOf("android4") > -1;
if(android4) {
$('html').addClass('android4');
}
var android2 = ua.indexOf("android2") > -1;
if(android2) {
$('html').addClass('android2');
}
@KruegerDesigns
Copy link
Author

Thank you @ctcherry for revising and teaching me better practices!


// adds mobile browser class to html tag. Special thanks to @ctcherry on github!
(function(){
    var ua = navigator.userAgent.toLowerCase().replace(/\s+/,'');
 
    var matchers = {
        ios: /(iphone|ipod|ipad)/,
        ipad: /ipad/,
        iphone: /(iphone|ipod)/,
        android: 'android',
        android2: 'android2',
        android4: 'android4'
    }
 
    var h = $('html');
 
    for (i in matchers) {
        var m = matachers[i];
        if ((typeof(m) == "string" && ua.indexOf(m) > -1) || (typeof(m) == "object" && ua.match(m))) {
            h.addClass(i)
        }
    }
 
})();

@sivakumar-kailasam
Copy link

@KruegerDesigns I don't mean to be a troll but matchers inside the for loop is spelled wrong, noticed it when I ran this as is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment