Books, Cats, Tech

"Everything that moves serves to interest and amuse a cat." — F.A. Paradis Moncrif

Vicki Brown

My home on the WWW
Est: 1994

Email: vlb@cfcl.com
Home

More About Me

Lifestream

Turny Triangles

Using JavaScript to "Hide/Show" a section

I've been collecting JavaScript code that allows me to hide/show sections of a web page. (You can see all of the relevant JavaScript, etc., by selecting View Source for this page.)
  1. I found some code at www.rgagnon.com that uses a pair of "Hide" and "Show" buttons.

    snap1.png

  1. The Sample code at support.internetconnection.net provides a choice of links which alternately "show" a different snippet of text in the same place.

    show a1         show 'thiscanbeanything'         show neither

    snap2.png
    snap3.png

  2. I especially liked the simple and elegant code at www.movalog.com. It doesn't get much smaller than this.

    Click to toggle

    snap4.png
But I wanted something a bit different.

I wanted...

Turny Triangles

(aka "disclosure triangles" :-)

How I Did It

I started with the super simple hide/show code from www.movalog.com. Then, I Googled for JavaScript code that swapped a pair of images. I found a simple and easy-to-understand example at javascript.internet.com. I merged the two bits of code together into one function, added some variables, grabbed a couple of GIFs, put it all together, and... Ta Da!

Here's the Code:

<script language="JavaScript">
<!-- Begin
var h_img_src = "hide.gif";
var s_img_src = "show.gif"

function toggle(id, img_name) {
  var e = document.getElementById(id);
  if(e.style.display == 'none') {
      e.style.display = 'block';
      document[img_name].src = s_img_src;
  } else {
      e.style.display = 'none';
      document[img_name].src = h_img_src;
  }
}
// End -->
</script>

And how to call it:

<a href="#Anchor" onclick="toggle('Block_1', 'Img_1');"
  ><img src="hide.gif" border=0 name="Img_1">Click Here</a>
<div id="Block_1"  style="display:none;">
Text to show or hide
</div>


Important

Whichever solution you choose, be sure to assign each div a unique ID.

       <div id="Block_1" style="display:none;">

If you also include a changing image, assign a unique name parameter to each image. It helps to give the div/img a mnemonic id/name pair.

       <img src="hide.gif" name="Img_1"> 
Otherwise, your clicks may hide/show unexpected sections of the page! Do a View Source to see what I mean.

Here are the images I use:

      hide.gif hide.gif

      show.gif show.gif