Javascript to Toggle Items


There are times when you will want to hide an item on a web page and activate the item only when the user clicks on an element. You can use a small bit of Javascript to display or hide the desired elements. In this example, I wrap up text, a table and a horizontal rule that I want to control inside of a <div> with an ID. The display of that <div> is controlled by the javascript function.

 <head>
 <Title>Toggle Sample</title>
 </head>
 <body>
 <script language="javascript">
 function toggleDisplay(id) {
 var obj = document.getElementById(id);
 obj.style.display = (obj.style.display == "none") ? "" : "none";
 return false; // cancel the href
 }
 </script>
 <h2> Some sample stuff</h2>
 <a href="#" onClick="return toggleDisplay('section1')">Stuff that Hides</a><br>
 <div id ="section1" style="display:none">
      Hello<br><!--  Say hello and build a simple table-->
      <table border="2">
      <tr>
      <td>
      A
      </td>
      <td>
      b
      </td>
      <td>
      C
      </td>
      </tr>
      <tr>
      <td>
      1
      </td>
      <td>
      2
      </td>
      <td>
      3
      </td>
      </tr>
 </table>
 <hr />
 </div>
 I do not hide!<br>
 
 </body>
</html>

You can show or hide the item by clicking on the element within the <a href=“#” …>, which is just text in this case. However, you can use other elements as well.


Leave a Reply

Your email address will not be published. Required fields are marked *