How to Create a Dynamic Collapsible Section in Javascript

Collapsible sections are very useful in hiding content and showing it only on demand. Few times its is required to make the collapsible section dynamic and sometimes it’s challenging. Here is the code I wrote in Perl and Javascript that creates a dynamic collapsible section.

<a href="javascript:collapsible('$div_instance','$imageID')">      
 <IMG id='$imageID' SRC='$imagePath' alt='(Expand / Collaspe Section' title='Expand / Collaspe' width=10 height=10>
  $display_header <br/>
</a>
<div id=$div_instance name=$div_instance style="overflow:hidden;display:$display_option;margin-left:30px; margin-top:20px;">
  <-- your content -->
</div>
<script language="JavaScript" type="text/javascript">
    <!--
     function collapsible(theID,imageID) {
          var elemnt = document.getElementById(theID);
          var imageObject =document.getElementById(imageID);
          if(elemnt.style.display == 'block') {
               elemnt.style.display ='none';
               imageObject.src='images/expand_icon.gif';
           }
           else{
           elemnt.style.display ='block';
           imageObject.src='images/expand_icon_down.gif';
           }
 
    }
    // -->
    </script>

Demo: https://jsfiddle.net/yLw54jh2/

Scroll to Top