Skip to content

Instantly share code, notes, and snippets.

@ackernaut
Created October 31, 2012 14:36
Show Gist options
  • Save ackernaut/3987381 to your computer and use it in GitHub Desktop.
Save ackernaut/3987381 to your computer and use it in GitHub Desktop.
Detect platforms, devices, etc.
// File: detection.js
(function($){
var htmlAttr = document.documentElement;
var ua = navigator.userAgent.toLowerCase();
// Global variables
isiPhone = ua.indexOf("iphone") > -1;
isiPad = ua.indexOf("ipad") > -1;
isiPod = ua.indexOf("ipod") > -1;
isAndroid = ua.indexOf("android") > -1;
isAndroid2 = ua.indexOf("android 2") > -1;
// Set data attributes
htmlAttr.setAttribute('data-useragent', navigator.userAgent);
htmlAttr.setAttribute('data-platform', navigator.platform);
// Set isiOS var
var isiOS = (isiPhone || isiPad || isiPod);
// Add classes for CSS
// iOS
if (isiOS) $(htmlAttr).addClass('ios');
if (isiPhone) $(htmlAttr).addClass('iphone');
if (isiPad) $(htmlAttr).addClass('ipad');
// Android
if (isAndroid) $(htmlAttr).addClass('android');
// Detect Android mobile (not tablet, probably mostly accurate per device UA)
// Setting these guys as global variables
if (isAndroid) { isAndroidMobile = ua.indexOf("mobile") > -1 } else { isAndroidMobile = false }
if (isAndroid) { isAndroidKindle = ua.indexOf("kindle") > -1 } else { isAndroidKindle = false }
if (isAndroidMobile) $(htmlAttr).addClass('android-mobile');
if (isAndroid && !isAndroidMobile) {
isAndroidTablet = true;
$(htmlAttr).addClass('android-tablet');
} else {
isAndroidTablet = false;
}
// Set smart device
if (isiOS || isAndroid) $(htmlAttr).addClass('smart-device');
// Set smartphone
if (isiPhone || isAndroidMobile) $(htmlAttr).addClass('smartphone');
// Set tablet
isAndroidTablet = false;
if (isiPad || isAndroidTablet) $(htmlAttr).addClass('tablet-device');
// Check if app mode is available and either enabled or disabled
if (("standalone" in window.navigator) && !window.navigator.standalone) {
$(htmlAttr).addClass('ios-app-mode-disabled');
}
if (("standalone" in window.navigator) && window.navigator.standalone) {
$(htmlAttr).addClass('ios-app-mode-enabled');
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment