[Javascript] DIV visibility

Nick Fitzsimons nick at nickfitz.co.uk
Mon Oct 9 14:10:15 CDT 2006


On 9 Oct 2006, at 19:24, SkyScanner wrote:

>
> The code I used to turn things on and off is rather old - its stuff  
> I just paste in, and haven't heard of a problem with it until now:
>
> /* Browser sensing */
> /* Set up boolian variables to record the browser type */
> var isNS4 = 0;
> var isIE4 = 0;
> var isNew = 0;
> var docObj, styleObj, currObj
>
> /* Determines the browser name and browser version */
> var brow = ((navigator.appName) + (parseInt(navigator.appVersion)));
>
> /* reassign variable depending on the browser */
> if (parseInt(navigator.appVersion >= 5)) {isNew = 1}
>  else if (brow == "Netscape4")
>  {isNS4 = 1;}
>   else if (brow == "Microsoft Internet Explorer4")
>   {isIE4 = 1;}
>
> if (isNS4||isIE4||isNew) {
>  docObj = (isNS4) ? 'document' : 'document.all';
>  styleObj = (isNS4) ? '' : '.style';
>  }
>
> dom = eval(docObj +  '.' + 'collect' + styleObj);
> dom.visibility = "hidden";
> dom = eval(docObj +  '.' + 'result' + styleObj);
> dom.visibility = "visible";
>
>

Not meaning to offend, but it's a long time since I've seen such a  
badly-written bit of JavaScript :-) As you say you pasted it in from  
elsewhere, I hope you won't take that personally.

The browser detection seems to date back to the last century, and  
won't work with Firefox, Safari, Opera and a number of other  
browsers; and it's only going to work with IE 6 by accident. In  
particular, on FF, Safari and Opera, neither docObj nor styleObj ever  
get created, meaning they both return a value of undefined. This  
means that the lines using eval will fail with an error. (Also, there  
is no possible reason to use eval in this way, and there never was.)

I will assume that support for IE4 and Netscape 4 is not high on your  
list of priorities. Try replacing all of the above code with the  
following:

if (document.getElementById) {
    document.getElementById("collect").style.visibility = "hidden";
    document.getElementById("result").style.visibility = "visible";
}

which will work in all modern browsers, and will fail silently on any  
particularly old browser.

Also, and forgive me if you're already aware of this, "visibility"  
won't prevent  a block from taking up space on the page; if you want  
the effect where the newly-revealed block occupies the same space as  
the newly-hidden block, use:

if (document.getElementById) {
    document.getElementById("collect").style.display = "none";
    document.getElementById("result").style.display = "block";
}

There are more elegant ways of doing this by switching values in and  
out of the "class" attribute, but this code should meet your needs,  
particularly if you want to get this fixed in a hurry :-)

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list