- Navigation -
Dynamically 'collapsing' things using Javascript

Here's a nifty little way to have a 'show/hide' button on your webpages for content that isn't needed all the time.
To start off, let's meet the CSS property 'display'. You can set this to several things, but the two we're looking at are 'block' and 'none'. We can use these to basically hide the content and show it again. An alternative way to hide the content would be to erase the HTML and put it back again using innerHTML, but to just show and hide it, this isn't needed.

<div style='display:none'>This content is invisible!</div>
<div style='display:block'>This content can be seen.</div>

To dynamically change the property, we need to give the <div> tag an id. We also need something to trigger the change, a hyperlink with an 'onclick' event. And one last thing, to avoid having to paste the code in several places, we're going to use a function that we can call.

<script language="JavaScript">

function toggleVisibility(me){
	if (me.style.display=="none"){
	} else {


<a href="#" onclick="toggleVisibility(document.all.subtext1);">Show/Hide Text</a>

<div id="subtext1" style="display: none">
 This text is shown and hidden dynamically!

Very simply, we declare the function called 'toggleVisibilty' which has one argument, 'me'. If me's display is none, set it to block, and visa versa. Then we have a hyperlink which goes to nowhere, with onclick set to call the function, with the argument document.all.subtext1. When this is clicked, the function will look for the first thing in all the document with the id 'subtext1' and toggle its visibility. Notice I set the div's style to start off hidden, you can start it off visible if you want. If you want to use it on more than one thing, just change the subtext1 to something else each time - you don't need to paste the function more than once. Also you can put the hyperlink as far away from the div as you like - hence the document.all part.

Click here to see it in action.

And that's all there is too it - you can put it around tables, quick reply forms, or just about anything you usually want to hide really.

- mitxela

© Kousou Games 2007 lowfi version
Page created in 0.007 seconds.
Valid XHTML 1.0 Transitional Valid CSS Powered by PHP