Friday, 19 October 2007

Show Hide Layer using a simple Javascript function

Are you looking for a simple JavaScript funciont to show/hide HTML elements? Take a look at this post.

This is the most simple Javascript function that I have written and used in some web projects usefull to show and hide a layer using CSS "display" property.

document.getElementById('id').style.display='block'

...to show the layer or...

document.getElementById('id').style.display='none'

... to hide the layer.

Download this script

How it works?
The script is very simple. The javascript function showlayer() has a parameter "layer", the layer ID that you want hide or show, for example:

<div id="myName">Antonio</div>


... in this example the layer ID is myName.

Now we will add a link that call the showlayer() function passing the layer ID:

<a href="#" onclick="javascript:showlayer('myName')">Hide / Show Layer </a>


Remember to add a link to show_layer.js into your page:

<script language="javascript" src="show_layer.js"></script>



The code
This is the code:

function showlayer(layer){
var myLayer = document.getElementById(layer).style.display;
if(myLayer=="none"){
document.getElementById(layer).style.display="block";
} else {
document.getElementById(layer).style.display="none";
}
}

No comments:

Post a Comment