Saturday, November 24, 2007

Easiest way to check IE version with JavaScript

Alright, so I needed a easy way to execute custom JavaScript for clients using versions of IE lower than 7. All the scripts Google showed me were really huge and quite outdated. So I took what I found, and turned it into something really lightweight. Note that this is just a quick hack, but so far it seems to be enough for my needs.

Code:


var Browser = {
Version: function() {
var version = 999; // we assume a sane browser
if (navigator.appVersion.indexOf("MSIE") != -1)
// bah, IE again, lets downgrade version number
version = parseFloat(navigator.appVersion.split("MSIE")[1]);
return version;
}
}


Which enables me to do stuff like this:


if (Browser.Version() < 7) {
... // if client is using IE6 or lower, run this code
}


..or this:


if (Browser.Version() >= 7) {
... // if client is using IE7 or a sane browser, run this code
}


It will simply return 999 if the browser is non-IE. Is it safe to assume that navigator.appVersion always will contain "MSIE" in uppercase?

18 comments:

zamkinos said...

thanks...

Anonymous said...

Thanks alot man! Worked good!

Anonymous said...

doesn't work for IE 8, I get version 7 as result

Rim said...

Thanks!

Anonymous said...

It worked for me in IE8. It will say 7 if you have IE8 in IE7 compatibility mode.

Phil said...

Slick. Just what I needed for a rush fix.

You are the man said...

You are genius

Keven said...

thanks so much!!! finally a solution that really work!!

Ankit Sharma said...

Thanks, worked fine.

Nada said...

Thanks! Works like a charm.

smNabil said...

Bingo!
You Rock my Dear :-)

Anonymous said...

IE7 is still insane... only IE9 is sane in my opinion.

Anonymous said...

Just what I was looking for. Thanks!

Anonymous said...

var isIE=0/*@cc_on+ScriptEngineMajorVersion()*/;

Anonymous said...

works great... thanks a lot mate..

Anonymous said...

This is a nice minification:
function ieversion(a){return a=navigator.appVersion,a.indexOf('MSIE')+1?parseFloat(a.split('MSIE')[1]):999}

Anonymous said...

thanks a lot!

Anonymous said...

Very helpful, Thanks a lot :)