Jump to content

expandable/collapsable list


RLJ

Recommended Posts

I have the following code to make a expandable/collapsable list.

 

<html>

<head>

<script language="JavaScript">

function expandcollapse(element)
{
    //if(document.getElementById(element).style.display =='block')
        //{document.getElementById(element).style.display ='none';}
    //if(document.getElementById(element).style.display =='none')
        {document.getElementById(element).style.display ='block';}
    
}

</script>

<style type="text/css">

body {
margin:50px;
background-color:#F9FAC7;
font: 18px/22px Verdana, arial, helvetica, sans-serif;
color:black;
}
.list { 
font: 14px/18px Trebuchet, Verdana, Arial, Helvetica, sans-serif;
}
.list a{
text-decoration:none;
color:green;

}
.list a:hover, #list a:focus {
text-decoration:overline;
border-bottom:1px solid purple;
color:purple;

}
#suba1, #suba2, #suba3,#subb1, #subb2, #subb3  {
display: none;
}

</style>

</head>


<body>


<div class="list">
<ul>
  <li>
<a href="#" onclick="expandcollapse('subb1')">List Item 1</a>
    <ul id="subb1">
      <li>Subb1-1</li>

      <li>Subb1-2</li>
    </ul>
  </li>
  <li>
<a href="#" onclick="expandcollapse('subb2')">List Item 2</a>
    <ul id="subb2">
      <li>Subb2-1</li>

      <li>Subb2-2</li>
    </ul>
  </li>
  <li>
<a href="#" onclick="expandcollapse('subb3')">List Item 3</a>
    <ul id="subb3">
      <li>Subb3-1</li>

      <li>Subb3-2</li>
    </ul>
  </li>
</ul>
</div>


</body>

</html>

 

As is, with the first 3 lines of Javascript commented out, when you click on the list item link, the list items expand, as expected.

 

However, when 'un-commenting-out' those 3 lines, I expected that when the link was clicked, the list items would expand and then if the link was clicked again, they would collapse again. This is not working and I don't understand why not.

 

Could someone help me out pls? Thanks!

Link to comment
https://forums.phpfreaks.com/topic/223295-expandablecollapsable-list/
Share on other sites

There's actually 2 issues.

 

The first is that the expand doesn't work because initially the display property is null.  You can see this if you stick an alert at the top of the function.  You can fix that by adding an:

|| document.getElementById(element).style.display =='''

 

And your expansion would work fine.

 

However, you will never get collapsing to work, because on collapse your function would:

 

-set display to = 'none'

- then immediately set it back to 'block'  (2nd if in function).

 

The if then else is the logical approach to making this work.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.