Java Script

Browser detection with jQuery

Here is a delicious little snippet to add custom browser classes using jQuery.

This code examines common browser types and adds a named class to the 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 (for Mac and PC) are detected using this method:

User AgentClass 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.

Leave a Reply

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

Back to top button
en_USEnglish