Detect IE 8 – 12 using simple JS

This is a simple JS to detect the version of IE from 8 – 11, which helped me write IE specific styles without any crazy IE Hacks or conditional statements.

This JS will add a class on the HTML tag(you can target any tag inside the HMTL) specific to that IE version.
Example you are on IE10 the html tag will be <html class=”ie ie10″>

Note: This JS needs to be placed before all you styles.

JSFiddle: https://jsfiddle.net/giri_jeedigunta/2ctoccs7/



(function(ua) {
     var browserData = ua,
         targetTag = document.getElementsByTagName("html")[0],
         ieInfo,
         className,
         versionNum;

     /* IE Check Starts */
     if (browserData.indexOf("MSIE ") > 0) {
         /* Check for IE 8, 9 */
         ieInfo = browserData.indexOf("MSIE ");
         versionNum = parseInt(browserData.substring(ieInfo + 5, browserData.indexOf(".", ieInfo)), 10);
     } else if (browserData.indexOf("Trident/") > 0) {
         /* Check for IE 10 */
         ieInfo = browserData.indexOf("rv:");
         versionNum = parseInt(browserData.substring(ieInfo + 3, browserData.indexOf(".", ieInfo)), 10);
     } else if (browserData.indexOf("Edge/")) {
         /* Check for IE 11 */
         ieInfo = browserData.indexOf("Edge/");
         versionNum = parseInt(browserData.substring(ieInfo + 5, browserData.indexOf(".", ieInfo)), 10);
     }
     /* IE Check Ends */

     // Adding the Class to the Targeted HTML Tag.
     className = "ie ie" + versionNum;
     if (isNaN(versionNum)) return !1;
     targetTag.setAttribute("class", className); // Example Output for IE 11: <html class="ie ie11">    

 }(window.navigator.userAgent));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s