...

View Full Version : show/hide script > allow only 1 open div at the time



oslofish
06-05-2006, 08:50 PM
Hello -

I have a show/hide script working nicely, but currently it is allowing more than 1 div to be opened at the time. How can I get it to collapse/hide one div when another is expanded?

Here is sample code:

The JavaScript:
--------------


// SHOW / HIDE CONTENT FUNCTION

function HideContent(d) {document.getElementById(d).style.display = "none";}
function ShowContent(d) {document.getElementById(d).style.display = "";}
function ReverseContentDisplay(d)
{if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "";
}else { document.getElementById(d).style.display = "none"; }}


The HTML:
----------
Trigger link:

<a href="javascript:ReverseContentDisplay('ca')">California</a>

Hidden div:


<div id="ca" class="city-list" style="display:none;">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="purple">
<tr>
<td colspan="5" align="right" valign="bottom"><a href="javascript:HideContent('ca')"><img src="assets/img/x-2.gif" alt="x" width="14" height="11" vspace="5" hspace="10" /></a></td>
</tr>
<tr>
<td width="30%"><a href="#">Alameda</a></td>
<td width="5%">&nbsp;</td>
<td width="30%"><a href="#">Indio</a></td>
<td width="5%">&nbsp;</td>
<td width="30%"><a href="#">Redlands</a></td>
</tr>
<tr>
<td><a href="#">Culver City</a></td>
<td>&nbsp;</td>
<td><a href="#">Mission Viejo</a></td>
<td>&nbsp;</td>
<td><a href="#">San Ramon</a></td>
</tr>
<tr>
<td><a href="#">Hancock Park</a></td>
<td>&nbsp;</td>
<td><a href="#">Palm Springs</a></td>
<td>&nbsp;</td>
<td><a href="#">Studio City</a></td>
</tr>
<tr>
<td colspan="5">&nbsp;</td>
</tr>
</table>
</div>


Your help would be greatly appreciated!

Thanks,
oslofish

Beagle
06-05-2006, 08:59 PM
You need to keep track of other open divs and close them when you call open. I suggest a global like this:



var g_openDiv;

function ShowDiv(div)
{
if (g_openDiv)
HideDiv(g_openDiv);

g_openDiv = document.getElementById(div);
g_openDiv.style.display = "";
}

oslofish
06-05-2006, 09:43 PM
Beagle,

Thanks for the reply, I appreciate it! My knowledge of JavaScript is still limited, however, so would you mind telling me how to incorporate this into the existing code?


oslofish

Beagle
06-05-2006, 10:23 PM
You need a global variable at the beginning of your script block:



<script type="text/javascript">
var g_openDiv;


then you need to modify your current function to do what I said:


function ShowContent(d)
{
g_openDiv = document.getElementById(d);
g_openDiv.style.display = "";
if (g_openDiv)
HideContent(g_openDiv);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum