michaelmcgurk michaelmcgurk - 3 months ago 6
CSS Question

Hide/Show element if IE - Javascript

I am working with a script that pops up an

alert
if the user is or isn't using IE.

Instead of this, I'd like to show or hide a
div
element in my page.

I have tried unsuccessfully here: http://fiddle.jshell.net/shhv1Lx3/2/

Working alert demo here: http://fiddle.jshell.net/shhv1Lx3/3/



function GetIEVersion() {
var sAgent = window.navigator.userAgent;
var Idx = sAgent.indexOf("MSIE");

// If IE, return version number.
if (Idx > 0)
return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));

// If IE 11 then look for Updated user agent string.
else if (!!navigator.userAgent.match(/Trident\/7\./))
return 11;

else
return 0; //It is not IE
}

var e = document.getElementById(ie);
var e2 = document.getElementById(chrome);

if (GetIEVersion() > 0)
alert("This is IE " + GetIEVersion());
e.style.display = 'block';
e2.style.display = 'none';
else
alert("This is not IE.");
e.style.display = 'none';
e2.style.display = 'block';

<div id="ie">
ie
</div>

<div id="chrome">
chrome
</div>




Answer

You should use {} when using if/else statements. The are optional when there is only one statement, but mandatory when there are multiple statements. I highly suggest using {} always, regardless of the number of statements.

You also need to pass a string to getElementById().

function GetIEVersion() {
  var sAgent = window.navigator.userAgent;
  var Idx = sAgent.indexOf("MSIE");

  // If IE, return version number.
  if (Idx > 0){
    return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));
  }
  // If IE 11 then look for Updated user agent string.
  else if (!!navigator.userAgent.match(/Trident\/7\./)){
    return 11;
  }
  else{
    return 0; //It is not IE
  }
}

var e = document.getElementById('ie');
var e2 = document.getElementById('chrome');

if (GetIEVersion() > 0){
   alert("This is IE " + GetIEVersion());
   e.style.display = 'block';
   e2.style.display = 'none';
}
else{
   alert("This is not IE.");
   e.style.display = 'none';
   e2.style.display = 'block';
}
<div id="ie">
ie
</div>

<div id="chrome">
chrome
</div>