-1

How to execute a code for all browsers except IE8 and lower using a single IF statement?

Slavik Meltser
  • 9,712
  • 3
  • 47
  • 48

2 Answers2

0

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.

Slavik Meltser
  • 9,712
  • 3
  • 47
  • 48
0

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]-->
Syph3R
  • 77
  • 9