Reputation: 251
Hoping someone with a better knowledge of javascript can assist, I am wanting to use the following to create an expand/collapse div on our site, however this is loading automatically as expanded where it needs to be loaded initially as being collapsed.
Here's the code:
<script type="text/javascript">
// toggle specific
function toggleDiv(id1,id2) {
var tag = document.getElementById(id1).style;
var tagicon = document.getElementById(id2);
if(tag.display == "none") {
tag.display = "block";
tagicon.innerHTML = " - ";
} else {
tag.display = "none";
tagicon.innerHTML = " + ";
}
}
function expandAll(cnt) {
for(var x=1; x<=cnt; x++) {
document.getElementById('content'+x).style.display="block";
document.getElementById('icon'+x).innerHTML=" - ";
}
}
function collapseAll(cnt) {
for(var x=1; x<=cnt; x++) {
document.getElementById('content'+x).style.display="none";
document.getElementById('icon'+x).innerHTML=" + ";
}
}
</script>
<style type="text/css">
.title {
padding:5px;
border:1px solid #CCCCCC;
font:15px arial;
width:300px;
cursor:pointer;
height:20px;
}
.item {
padding:5px;
border:1px solid #CCCCCC;
font:12px verdana;
width:300px;
}
.item div {
border-bottom:1px dashed #CCCCCC;
padding:5px;
}
.button {
border:1px solid #CCCCCC;
padding:5px;
cursor:pointer;
}
</style>
</head>
<body>
</div>
<div class="title" onClick="javascript:toggleDiv('content1','icon1');">
<span style="float:left">Sample Title 1</span>
<span id="icon1" style="float:right"> - </span>
</div>
<div id="content1" class="item">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
<div class="title" onClick="javascript:toggleDiv('content2','icon2');">
<span style="float:left">Sample Title 2</span>
<span id="icon2" style="float:right"> - </span>
</div>
<div id="content2" class="item">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
Upvotes: 2
Views: 8394
Reputation: 2381
There are two ways of doing this. For one, you could start all of your html as in the collapsed state by replacing the -'s with +'s and using appropriate css stylings. Alternatively, as suggested you can bind the collapseAll to onload - I would recommend looking at Best practice for using window.onload for best practices surrounding window.onload, as you can run into nasty behavior if you aren't careful
Upvotes: 2
Reputation: 664548
<div class="title" onclick="javascript:toggleDiv('content1','icon1');">
^ should be lowercase
<span style="float:left">Sample Title 1</span>
<span id="icon1" style="float:right"> + </span>
^ should expand
</div>
<div id="content1" class="item" style="display:none;">
^ should be hidden ^
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
But note that non-JS users won't see anything then.
Upvotes: 1