How can I adapt the following code so that one of the divs will be open when the page is first loaded but will close when other divs are opened?
As it is now, the code hides the open div when another is open but only if that div is closed when the page is loaded.
I found the code here: Hiding a div when another is shown So credit to whoever posted it.
<body>
<script language="javascript">
function MyFunction(divName){
//hidden val
var hiddenVal = document.getElementById("tempDivName");
//hide old
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
//show div
var tempDiv = document.getElementById(divName);
tempDiv.style.display = 'block';
//save div ID
hiddenVal.Value = document.getElementById(divName).getAttribute("id");
}
</script>
<input id="tempDivName" type="hidden" />
<ul>
<li><a href="#" OnClick="MyFunction('myDiv1');">Show myDiv1</a></li>
<li><a href="#" OnClick="MyFunction('myDiv2');">Show myDiv2</a></li>
<li><a href="#" OnClick="MyFunction('myDiv3');">Show myDiv3</a></li>
</ul>
<br/>
<div id="myDiv1" style="background-color:red; height:200px; width:200px; display:none">
myDiv1
</div>
<div id="myDiv2" style="background-color:yellow; height:200px; width:200px; display:none">
myDiv2
</div>
<div id="myDiv3" style="background-color:green; height:200px; width:200px; display:none">
myDiv3
</div>
</body>
This is how I've adapted it so far to make it so each subsequent div can be accessed from the open div, but none of my (inexpert) tinkering has been able to make the code work when the first div in open to begin with, nor have I been able to find the answer using a search engine.
<body>
<script language="javascript">
function MyFunction(divName){
//hidden val
var hiddenVal = document.getElementById("tempDivName");
//hide old
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
//show div
var tempDiv = document.getElementById(divName);
tempDiv.style.display = 'block';
//save div ID
hiddenVal.Value = document.getElementById(divName).getAttribute("id");
}
</script>
<input id="tempDivName" type="hidden"/>
<div align="center"><a href="#" OnClick="MyFunction('myDiv1');">Contents</a></div>
<div id="myDiv1" style="display:none">
<a href="#" OnClick="MyFunction('myDiv2');">Page 1</a>
<br/>
<a href="#" OnClick="MyFunction('myDiv3');">Page 2</a>
</div>
<div id="myDiv2" style="display:none">
<div align="right"><a href="#" OnClick="MyFunction('myDiv3');">Page 2 ►</a></div>
<br/>
text page 1
</div>
<div id="myDiv3" style="display:none">
<a href="#" OnClick="MyFunction('myDiv2');">◄ Page 1</a>
<br/>
<br/>
text page 2
</div>
</body>