Search code examples
javascriptif-statementexpand

javascript expand/collapse text - collapse on default


I'm very inexperienced in javascript but have managed (with the help of google) to put together the following expandable/collapsible link

<script type="text/javascript">
function toggleMe(a) {
   var e = document.getElementById(a);
   if(!e) return true;

   if(e.style.display == "none") {
      e.style.display = "block"
   }
   else {
      e.style.display = "none"
   }
   return true;
}
</script>
<p>
  <input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
</p>
<p id="para1">
   <strong><em>text text text text</em></strong>
</p>

The only problem with it is that it is expanded by default and I wanted it collapsed by default. Can anyone help with this? Thank you! Also, if anyone knows how to get +/- signs next to the link that change depending on whether it is expanded or collapsed, that would be great.


Solution

  • <script type="text/javascript">
    function toggleMe(a) {
       var e = document.getElementById(a);
       var toggleIcon = document.getElementById('toggle-icon');
       if(!e) return true;
    
       if(e.style.display == "none") {
          e.style.display = "block";
          toggleIcon.innerHTML = '-';
       }
       else {
          e.style.display = "none";
          toggleIcon.innerHTML = '+';
       }
       return true;
    }
    </script>
    <p>
      <input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
      <span id="toggle-icon">+</span>
    </p>
    <p id="para1" style="display: none;">
       <strong><em>text text text text</em></strong>
    </p>