Page 1 of 1
Strange javascript error
Posted: Fri Jan 05, 2007 6:16 pm
by thiscatis
This one works in FF:
Code: Select all
var state = 'hidden';
function showhide(layer_ref) {
if (state == 'visible') {
state = 'hidden';
}
else {
state = 'visible';
}
if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref + ".style.visibility = state");
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].visibility = state;
}
if (document.getElementById && !document.all) {
maxwell_smart = document.getElementById(layer_ref);
maxwell_smart.style.visibility = state;
}
}
But in IE I get:
Error: Expected ";"
feyd | syntax for Javascript is with a lower case "j" 
Posted: Fri Jan 05, 2007 6:34 pm
by Kieran Huggins
Don't know what the problem is.. but here's a better one:
Code: Select all
function showhide(element) {
if(typeof(element)=='string') element = document.getElementById(element);
if(element.style.visibility=='hidden'){
element.style.visibility='visible';
}else{
element.style.visibility='hidden';
}
}
You shouldn't use the "document.all" type of test - instead do feature detection (if you have to), like:
Code: Select all
if(element.someFunction) output = element.someFuntion('sadsa')
The feature's existance is the thing you actually care about, and this way it won't break in the future if the browser supports document.all but stops supporting the function you want.
Incidentally, there's no need for browser detection in this case.
Posted: Fri Jan 05, 2007 10:57 pm
by volka
Kieran Huggins wrote:Incidentally, there's no need for browser detection in this case.
unless you want to support old browsers like the script suggests
//IS NETSCAPE 4 or below
Posted: Sat Jan 06, 2007 3:05 am
by Kieran Huggins
volka wrote:Kieran Huggins wrote:Incidentally, there's no need for browser detection in this case.
unless you want to support old browsers like the script suggests
//IS NETSCAPE 4 or below
In which case feature detection would still work:
Code: Select all
if(element.style.visibility){ // for CSS browsers
//...
}else if(document.createElement){ // for non-CSS browsers
window.waitingRoom = document.createElement('div'); // make an invisible div
waitingRoom.appendChild(element); // move the element to this div
}
The general idea it to not assume a feature exists or doesn't based on a the presence or absence of a different feature. Javascript will let us test every features existence.
Instead of using:
Code: Select all
if(feature_one exists) do function_two
we can instead use:
Code: Select all
if(function_two exists) do function_two