Skip to content

Instantly share code, notes, and snippets.

@jalbertbowden
Forked from peteboere/ie-mobile-detect.js
Last active April 7, 2020 10:30
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jalbertbowden/5174156 to your computer and use it in GitHub Desktop.
Save jalbertbowden/5174156 to your computer and use it in GitHub Desktop.
JavaScript IE Version Detection, IE6-10 and IE Mobile
// ----------------------------------------------------------
// A short snippet for detecting versions of IE:
// Uses a combination of object detection and user-agent
// sniffing.
// ----------------------------------------------------------
// If you're not in IE then:
// ie === NaN // falsy
// If you're in IE then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9 ...
// ie < 9 // Anything less than IE9
// script needs to be wrapped on conditional comments to exclude > ie9
// appends class of "ieX" where X is version number, to document's html element
// ie8 demo http://dev.bowdenweb.com/ua/browsers/ie/ie8-detection.html
// ie9 demo http://dev.bowdenweb.com/ua/browsers/ie/ie9-detection.html
var ie = ( !!window.ActiveXObject && +( /msie\s(\d+)/i.exec( navigator.userAgent )[1] ) ) || NaN;
if (ie === 6) {
document.documentElement.className+=' ie6';
} else if (ie === 7) {
document.documentElement.className+=' ie7';
} else if (ie === 8) {
document.documentElement.className+=' ie8';
} else if (ie === 9) {
document.documentElement.className+=' ie9';
}
// The same thing but for IE Mobile instead.
var ieMobile = ( !! window.ActiveXObject && +( /IEMobile\/(\d+\.?(\d+)?)/.exec( navigator.userAgent )[1] ) ) || NaN;
// ie10 doesn't support conditional comments but it does support @cc_on
// @cc_on activates conditional comments within a script
// appends class of "ie10" to the document's html element
// http://msdn.microsoft.com/en-us/library/8ka90k2e%28v=vs.94%29.aspx
// demo http://dev.bowdenweb.com/ua/browsers/ie/ie10-detection-via-cc.html
<!--[if !IE]><!--><script>if(/*@cc_on!@*/false){document.documentElement.className+=' ie10';}</script><!--<![endif]-->
@anhr
Copy link

anhr commented Aug 4, 2015

Sometimes I see "Unable to get property '1' of undefined or null reference" because
/IEMobile/(\d+.?(\d+)?)/.exec( navigator.userAgent ) is null
if "IEMobile" string is not exists in the navigator.userAgent.
I have used a code below for resolving of problem:

var ieMobile = /IEMobile/(\d+.?(\d+)?)/.exec( navigator.userAgent );
ieMobile = ( !! window.ActiveXObject && ieMobile && (ieMobile.length >= 2) && +( ieMobile[1] ) ) || NaN;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment