What is wrong with this Javascript code?

Hi,

I am trying to use Javascript to sniff the browser and if it is IE then display one div “ie” and if not IE then display div “non-ie”.

But the If else part that contains the actual command to display a given div is not firing at all. As you can see I have put a alert command in each section just for debugging purposes and these alerts dont even fire! So what is wrong with this JavaScript please:

<script language="JavaScript">

var isIE = window.ActiveXObject ? 1 : 0;

alert("Is Browser IE: " + isIE);

if (isIE == 1)
  {
  // code for IE6, IE5
  document.getElementById('ie').style.display = 'block';
  alert("Browser is IE");

  } else if (isIE == 0) {

  // code for Firefox, Chrome, Opera, Safari
  document.getElementById('non-ie').style.display = 'block';
  alert("Browser is NOT IE");

  }

</script>

ThanX,
Dean.

Normally there are cross-browser techniques that, depending on what you want to achieve, work well across all browsers. You really should investigate those instead.

Detecting browser types is a technique that belongs in the last century, and should remain there.

Do you have elements on the page with the appropriate unique identifiers? Or perhaps, are you running the script before those parts of the page exist?

Hi,

No, “console error messages”.
I did not even think such an error message was possible in case of Javascript.

Any console error messages?

This in-line code must not precede the elements to which it refers.

Thanks for the sage advice :slight_smile:

But can you tell me why the code between the IF Else is not firing at all?
I mean the code above it is firing, but not the code between the IF Else, not even to the point of the alerts firing!

Well I must say this was a good learning experience.
That is the reason that Javascript was not running was that the code that turned on the div element was loaded before the body of the page, so it was not running because I guess the way JS is designed is that the divs must load 1st before it can see the divs!

So I moved the Javascript to after the body, and now it works fine.

Very interesting!

Thanx for your tip.
Dean.