How to execute a code for all browsers except IE8 and lower using a single IF statement?
-
2Why do you want to do that. Are you sure you are not looking for feature detection instead of browser detection? – PeeHaa Oct 27 '13 at 15:46
-
The best approach really depends on what the "something" is. – Wesley Murch Oct 27 '13 at 15:49
-
PeeHaa, because IE8 and lower doesn't support some CSS, JavaScript commands and XDomain AJAX calls that that is mandatory for my software! – Slavik Meltser Oct 27 '13 at 16:00
-
2I would encourage to test on functionality, rather than if the user is using a certain browser. – Sumurai8 Oct 27 '13 at 16:00
-
Wesley Murch, something is a code. And the duplication you posted is not entirely answer my question. I need it in a single line. But I think I found it, posted an answer here. – Slavik Meltser Oct 27 '13 at 16:03
-
Sumurai8, it's impossible on my case. – Slavik Meltser Oct 28 '13 at 07:47
2 Answers
I found an answer, and it's pretty simple:
if ( parseFloat((navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]*)/)||[0,9])[1])>=9 ) {
//do something for all browsers and IE9+
} else {
//do something only for IE8 and lower
}
Explanation:
The navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]*)/)
will return an array includes the whole string in index 0, and the version in index 1. If the match not found, it will return NULL.
Once the phrase returns a NULL, it will use the next operand [0,9]
, with the version 9 in index 1 (the lowest version of IE you are looking for).
Then, I take the value of index 1 and checking if it's greater or equal to 9.
So what does it means?
It means that every browser that is not IE will pass the IF, because the match will always return NULL, it will take the default array and finally check if 9>=9
, which is alway true.
If the browser is IE, it will take the actual version of the browser, and will check it. In that case all IE9+ versions will pass the IF statement, and for the rest it will fail.
Hope it clear enough.

- 9,712
- 3
- 47
- 48
If it is only about HTML or CSS stuff, you can use conditional comments in your .html file instead of JavaScript. http://www.quirksmode.org/css/condcom.html
In your case,
<!--[if lte IE 8]>
Cool stuff for IE 8
<![endif]-->
EDIT
<!--[if gte IE 8]>
Cool stuff for IE greater than IE 8
<![endif]-->

- 77
- 9
-
I familiar with this thing, But the problem is that my code injected dynamically. – Slavik Meltser Oct 27 '13 at 16:04
-
OK, so replace lte by gte, and you can use the logic explained here http://stackoverflow.com/questions/1692129/conditional-comment-for-except-ie8 – Syph3R Oct 27 '13 at 16:15
-