...

View Full Version : using a function to hide or show layers



alexhob
04-27-2004, 12:49 PM
I am new to JS and am struggling with a function I found on the net that shows or hides a layer. The function has the name of the layer hard coded into it. However I want to use the function by several links and so want to pass the layer name as a parameter. Can anyone show me how to do this?

Thanks.

function showorhide(v){
if(v){
visi="visible";
}
else{
visi="hidden";
}

//NN4
if(document.layers){

document.fred.visibility=visi;
}

//IE
if(document.all){

document.all.fred.style.visibility=visi;
}

//NN6
if(document.getElementById){

document.getElementById("fred").style.visibility=visi;
}
}

<div id="fred" style="position:relative;left:10;top:0;background-color:#FF0000;width:100; visibility:hidden;font-size:16px;color:white;font-weight:600">Hi, I'm fred</div>
<CENTER><A class="bodylink" id="lshow" href="javascript:void(0)" onClick="showorhide(1, fred);">show layer</A> | <A class="bodylink" href="javascript:void(0)" onClick="showorhide(0);">hide layer</A></CENTER>

glenngv
04-27-2004, 01:06 PM
function showorhide(v,layerId){
if(v){
visi="visible";
}
else{
visi="hidden";
}

//NN6+/IE5+ and other modern browsers
if(document.getElementById){
document.getElementById(layerId).style.visibility=visi;
}
//IE4+
else if(document.all){
document.all[layerId].style.visibility=visi;
}
//NN4
else if(document.layers){
document.layers[layerId].visibility=visi;
}
}
...
<A class="bodylink" href="#" onClick="showorhide(0,'fred');return false">hide layer</A>

I re-ordered the if-statements and put else-statements for efficiency.
Since IE5+/NN6+ are the prevalent browsers, you should check for that first.

alexhob
04-27-2004, 01:15 PM
Thanks a lot.

Can you explain why the parameter name has to be in either () or [] and when to chose/where to apply either?

Thanks.

glenngv
04-27-2004, 01:25 PM
You use () for methods/functions and [] for collections/arrays.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum