When defining variable directly, it works. Like the following code, the background color of body will be light green in IE and will be light blue in non-IE browsers.
<html>
<body>
<script>
if (window.attachEvent) {
var YourBrowserIsIE = true;
}
if (YourBrowserIsIE) {
document.body.style.backgroundColor = 'lightgreen';
}
else {
document.body.style.backgroundColor = 'lightblue';
}
</script>
</body>
</html>
However, sometimes the variable need to be defined using eval(), like the following, but the result will show an error saying that YourBrowserIsIE
is undefined in non-IE browsers.
if (window.attachEvent) {
eval('var YourBrowserIsIE = true;');
}
Yes, I know I can predefine var YourBrowserIsIE = false;
for non-IE browsers or change the if statement to if (typeof YourBrowserIsIE != 'undefined')
, but I want to keep the code as minimum as possible.
So is there a solution to use eval() to define the variable and check the variable using the straightforward if (YourBrowserIsIE)
without showing any error in non-IE browsers?
== EDIT ==
Sorry for being unclear. The situation of using eval() being mentioned above is actually for detecting IE version. Please see the following code.
<html>
<body>
<script>
if (window.attachEvent) {
var version = /msie (\d+)/i.exec(navigator.userAgent)[1];
eval('var YourBrowserIsIE' + version + ' = true;');
}
if (YourBrowserIsIE9) {
document.body.style.backgroundColor = 'lightgreen';
}
else {
document.body.style.backgroundColor = 'lightblue';
}
</script>
</body>
</html>