Show and Hide DIV Layers
May 12, 2005 7:42 AM   Subscribe

What is your favorite method for showing and hiding a DIV layer?

I'm wanting to clean up my site's column content and want clickable/drop-down layers. So it says 'Links' and a user clicks on the 'Links' and the list of links appears underneath.

Extra points for cross-browser, degradable and/or XHTML. Thnx!
posted by ao4047 to Computers & Internet (7 answers total) 2 users marked this as a favorite
 
div.style.display = (show ? "block" : "none");

or

div.style.visibility = (show ? "visible" : "hidden");

or

if (show) {
  parentNode.appendChild(div);
}
else {
  parentNode.removeChild(div);
}


or

<style>
  .visible { display: block; }
  .invisible { display: none; }
</style>

div.class = (show ? "visible" : "invisible");

posted by Khalad at 7:56 AM on May 12, 2005


Response by poster: (not sure how that fits into an OnClick JavaScript href?)
posted by ao4047 at 8:09 AM on May 12, 2005


<html>
<head>
.
.
<style>
div#myToggledDiv {display: none;}
</style>
.
<script type="text/javascript>
function swapMyToggledDiv()
{
if(document.getElementById("myToggledDiv").style.display = "block")
{
document.getElementById("myToggledDiv").style.display = "none";
}
else
{
document.getElementById("myToggledDiv").style.display = "block";
}
</script>
.
.
</head>
<body>
.
.
<div id="myClickyDiv" onClick="swapMyToggledDiv();">clicky stuff happens here</div>
.
.
<div id="myToggledDiv">the display of this is toggled</div>
.
.
</body>
</html>

...is probably the easiest way to do it.
posted by normy at 8:44 AM on May 12, 2005


Best answer: Normy's got it. But if can be improved:

<div id="myClickyDiv" onclick="toggleDisplay('myToggledDiv')">

and then you can create a more generic function:
<script type="text/javascript">
function toggleDisplay(divId) {
  var div = document.getElementById(divId);
  div.style.display = (div.style.display=="block" ? "none" : "block");
}
</script>

posted by furtive at 10:57 AM on May 12, 2005


Oh, special note, if you are using it in the onclick of an anchor, then be sure to return false else the href will navigate it to the top of the document. e.g.

<a href="#" onclick="someFunc('blah');return false;">show/hide</a>
posted by furtive at 11:00 AM on May 12, 2005


There's an error in norm's if. It should be:
if (document.getElementById("myToggledDiv").style.display == "block")

posted by gentle at 2:56 PM on May 12, 2005


Yes, been looking for this specific piece of code. Thanks guys...
posted by sprockett at 11:36 AM on November 29, 2005


« Older Neuraesthenia?   |   What are Probiotics, and do I need them? Newer »
This thread is closed to new comments.