Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

jordanste

macrumors member
Original poster
Feb 25, 2006
83
0
i am trying to write an archive list that is collapsable and organized by month. im sure youve seen something identical on many sites as its pretty commonplace. i just dont know a lick of javascript.

i have my list laid out like this:

HTML:
<ul>
 <li>month1
  <ul>
   <li>article1</li>
   <li>article2</li>
   <li>etc...</li>
  </ul>
 </li>
 <li>month2
  <ul>
   <li>article1</li>
   <li>article2</li>
   <li>etc...</li>
  </ul>
 </li>
</ul>


i want the month names to be links that will collapse or show the child lists, anyone know how i could do this? thanks!
 
This is a pretty simple thing really. Here's a slightly altered bit of HTML:
HTML:
<ul>
 <li><span onclick="Collapser(this)">month1</span>
  <ul>
   <li>article1</li>
   <li>article2</li>
   <li>etc...</li>
  </ul>
 </li>
 <li><span onclick="Collapser(this)">month2</span>
  <ul>
   <li>article1</li>
   <li>article2</li>
   <li>etc...</li>
  </ul>
 </li>
</ul>
Here's the JavaScript:
PHP:
function Collapser(item)
{
  // Make sure the tags are setup correctly, if not just return
  if (!item.parentNode.getElementsByTagName("ul")[0]) return;
  var x = item.parentNode.getElementsByTagName("ul")[0];
  // if already visible, make disappear, otherwise reappear
  x.style.display = (x.style.display == "") ? 'none' : "";
}
You would then want to use CSS on the span tags to style them in such a way to make them appear clickable (colored differently, dashed border, etc.). Also, though you could setup the default CSS to have everything collapsed, that would trap the sub-links from visitors who do not have JavaScript enabled (like me). You could add some JavaScript to collapse them when the page loads, but would involved more coding.
 
Heres something I threw toghether,

HTML:
<html>
<head>
<style type="text/css">
#style1 {display: none;}
</style>

<script language="JavaScript">
    function hideshow(){
    if(document.getElementById('style1').style.display=='none'){
	document.getElementById('style1').style.display='block';
     }else{
	document.getElementById('style1').style.display='none';}}
</script>
</head>
<body>
	
<ul>
 <li><a href="javascript:hideshow();">Month</a>
  <ul id="style1">
   <li>article1</li>
   <li>article2</li>
   <li>etc...</li>
  </ul>
 </li>
 <li>month2
  <ul>
   <li>article1</li>
   <li>article2</li>
   <li>etc...</li>
  </ul>
 </li>
</ul>
	</body>
</html>

Thats the basic concept right there, hiding / showing Divs with js. Search google for collapsible divs, thats exactly what your looking for.

You can even send the div ID via javascript for multiple show/hides ex: javascript:hideshow('style');
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.