Detecting if IE7 or lower with conditional comments and javascript not working

I'm trying to check if a person is using anything IE with version less than 8 or anything else.

I use conditional comments to declare boolean..

<!--[if lt IE 8]>
<script type="text/javascript">var badIE = true;</script>
<![endif]-->

And now I check in my js file the boolean like this:

if (badIE == true){
    alert('You have bad IE!');
} else {
    alert('Bueno!');
}

If I use IE7 or IE6, it alerts that "You have bad IE!". If I use anything else, it should alert "Bueno!", but it does not. What is the problem?

Answers


You need to declare the badIE variable as false first in order for it to work, or else the code outside of the conditional knows nothing about badIE

Try this:

<script>
    var badIE = false;
</script>

<!--[if lt IE 8]>
<script type="text/javascript">badIE = true;</script>
<![endif]-->

<script>
if (badIE == true){
    alert('You have bad IE!');
} else {
    alert('Bueno!');
}
</script>

Not a direct answer (Neal has you covered), but you may also be interested in: http://code.google.com/p/ie7-js/

From the page: IE7.js is a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. It fixes many HTML and CSS issues and makes transparent PNG work correctly under IE5 and IE6.

Though if you're using jQuery, keep in mind that it does many of the same things as this library.


Your conditional statement <!--[if lt IE 8]> ... <![endif]--> means that the code between those will not be executed if the web browser is not an IE version less than 8, which means var badIE will never be declared for all other browsers (i.e., FireFox, IE8, IE9, Safari, etc.)

Because it is never declared, you are getting a silent scripting error in the background when the browser tries to execute if (badIE == true){, which means the browser immediately stops reading the script and does not try to execute the alert('Bueno!'); statement.


Need Your Help

Why does std::accumulate behave like this with standard arrays?

c++ arrays pointers c++11

I'm just getting into C++ and I think I have a handle on pointers, but std::accumulate() has me confused.

Restore database backup over the network

sql-server database sql-server-2005 backup restore

How do you restore a database backup using SQL Server 2005 over the network? I recall doing this before but there was something odd about the way you had to do it.