Add Internet Explorer class to body to detect old browser

When you have clients that still uses an old browser, you need to handle it. This javascript function detects the…

February 27, 2017

When you have clients that still uses an old browser, you need to handle it.
This javascript function detects the Microsoft browsers and add specific version for each one, so you can determine which browser is with CSS or with jQuery by controlling the class.
It adds a class msie | trident | edge to the body, together with a class ieXX, where XX is the browser version.

/**
* detect IE
* and add a specific class to the body
* function modified from this: http://stackoverflow.com/questions/19999388/check-if-user-is-using-ie-with-jquery
*/
function addIEclasses() {
	var ua = window.navigator.userAgent;
	var b = "";
	var msie = ua.indexOf('MSIE ');
	if (msie > 0) {
		// IE 10 or older => return version number
		b = "msie ie" + parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
	}

	var trident = ua.indexOf('Trident/');
	if (trident > 0) {
		// IE 11 => return version number
		var rv = ua.indexOf('rv:');
		b = "trident ie"+parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
	}

	var edge = ua.indexOf('Edge/');
	if (edge > 0) {
		// Edge (IE 12+) => return version number
		b = "edge ie"+parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);

	}

	// other browser
	if(b!="") {
		$('body').addClass(b);
	}
}

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

Stop sending email to new user in WordPress admin registration

Prevent WordPress to send notification emails when you manually create new users

March 9, 2017

Add filter on wp_title not working with Yoast SEO plugin

For SEO purposes, in a specific template that has a list of items with pagination, I need to have different…

February 22, 2017

Generate all old PDF preview images with WordPress 4.7

WordPress 4.7 generates thumbnails for PDF files while uploading them in the media library, this is a really good thing…

December 13, 2016

Modify list counter in :before pseudo class with jQuery using start attribute

Suppose you have two ordered list ol tags, and the second one has a start attribute. You also have in…

April 20, 2016

Clean up and optimize WordPress head tag

If you need to know how to remove RSS Feed URL’s from page head or how to remove post relational…

December 11, 2015

Embedding images in HTML or CSS with PHP

This small function returns an encoded string to embed images, inline, inside your html/css code and reduce the number of…

December 4, 2013