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

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Recommended

Scroll to DIV by ID without jQuery

Use scrollIntoView instead of jQuery animate.

December 16, 2022

React links

Collection of links and notes while approaching React.js, next.js and related topics.

December 14, 2022

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

Refresh a Google Adsense banner with Javascript

Often bloggers and site owners use galleries to have a greater number of pages, adding pages means adding clicks. Each…

November 9, 2013

Detect if is mobile with Javascript, read user agent

How to detect if your user is using a mobile device in Javascript? You can do it by checking the…

November 5, 2013

Unobtrusive javascript to add an overlay banner

If you have to add an overlay to a site, here is a fast way to do it with an…

November 7, 2011