WordPress Code Snippets

A fresh mix of code snippets and tutorials

jQuery browser detection

85

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:

  • Opera – .opera / .opera-pc
  • Webkit – .webkit / .webkit-pc
  • Mozilla – .mozilla / .mozilla-pc
  • Internet Explorer 9 – .ie9 (PC only)
  • Camino – .camino (Mac only)
  • Chrome – .chrome / .chrome-pc
  • iPad/iPod/iPhone – .apple
  • Safari – .safari / .safari-pc

Customize as needed by removing unnecessary browsers and adding new ones.


Show Support

Like our new Facebook Page to show support!