jQuery browser detection
Here’s a tasty little snippet for adding custom browser classes using jQuery.
This code checks for common browser types and adds a named class to the <html>
element.
// custom browser classes
$(document).ready(function(){
if (navigator.userAgent.indexOf('Mac OS X') != -1) {
// Mac
if ($.browser.opera) { $('html').addClass('opera'); }
if ($.browser.webkit) { $('html').addClass('webkit'); }
if ($.browser.mozilla) { $('html').addClass('mozilla'); }
if (/camino/.test(navigator.userAgent.toLowerCase())){ $('html').addClass('camino'); }
if (/chrome/.test(navigator.userAgent.toLowerCase())) { $('html').addClass('chrome'); }
if (navigator && navigator.platform && navigator.platform.match(/^(iPad|iPod|iPhone)$/)) { $('html').addClass('apple'); }
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) { $('html').addClass('safari'); }
} else {
// Not Mac
if ($.browser.opera) { $('html').addClass('opera-pc'); }
if ($.browser.webkit) { $('html').addClass('webkit-pc'); }
if ($.browser.mozilla) { $('html').addClass('mozilla-pc'); }
if (document.all && document.addEventListener) { $('html').addClass('ie9'); }
if (/chrome/.test(navigator.userAgent.toLowerCase())) { $('html').addClass('chrome-pc'); }
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) { $('html').addClass('safari-pc'); }
}
});
The following browsers are detected (for Mac & PC) using this method:
User Agent | Class Name |
---|---|
Camino | .camino (Mac only) |
Chrome | .chrome , .chrome-pc |
IE 9 | .ie9 (PC only) |
iPad/iPod/iPhone | .apple |
Mozilla | .mozilla , .mozilla-pc |
Opera | .opera , .opera-pc |
Safari | .safari , .safari-pc |
Webkit | .webkit , .webkit-pc |
Customize as needed by removing unnecessary browsers and adding new ones.