Wednesday, December 11, 2013

IE Check and IE Version Check in JavaScript

Hi,

If you want to provide certain JavaScript functionality which is specific to IE browser, or specific to a version of IE Browser, you would surely find below code helpful, in terms of detecting browser and its version.


Below is the variable that would hold Boolean value; It is TRUE when the browser is IE, FALSE otherwise.


var BrowserIE = {
  Check: function() {
var isIE = eval("/*@cc_on!@*/!1"); 
return isIE;
}
}

}

Below is the variable, that would hold true IE version, in form of AA.BB.CCCC.DDDDD, as can be seen in  IE Help Menu.

var BrowserVersion = {
          Check: function() {
                var e, obj = document.createElement("div"), x,
                   verIEtrue = null,
                   CLASSID = [
                       "{45EA75A0-A269-11D1-B5BF-0000F8051515}",
                       "{3AF36230-A269-11D1-B5BF-0000F8051515}",
                       "{89820200-ECBD-11CF-8B85-00AA005B4383}"
                           ];

                try{obj.style.behavior = "url(#default#clientcaps)"}
                catch(e){ };

                for (x=0;x
                {
                   try{verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g,".")}
                   catch(e){ };
                   if (verIEtrue) break;
                };

                return verIEtrue || void 0;
        }
}

You can copy above scripts in to your JS, AS-IS.

Above variables can be used to make your code conditional based on browser type and browser version.


Please check below example for understanding:


function doSomething() {

        if (BrowserIE.Check()) {
                alert('Browser is IE');
                //IE Browser Specific Functionality
        }
        else{
                alert('Browser is IE');
                //NON-IE Browser Specific Functionality
        }

        
        if (BrowserVersion.Check().substr(0,1) > 8) {
                alert('Browser IE : Version 9 or above');
                //IE Browser Version 9 or above Specific Functionality
        }
        else
        {
                alert('Browser IE : Version 8 or less');
                //IE Browser Version 8 or below Specific Functionality        
        }

}

No comments:

Post a Comment