Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications

Expand or Collapse Text with JavaScript

This is a simple script to expand and collapse text using DHTML. Try it here:

Click here to hide

Contents of the p tag



Here is the JavaScript function:
function expand(thistag, tag) {
   styleObj=document.getElementById(thistag).style;
   if (styleObj.display=='none')
   {
   	styleObj.display='';
	tag.innerHTML = "Click here to hide";
   }
   else {
   	styleObj.display='none';
    tag.innerHTML = "Click here to show";
   }
}


<div id="div1" onclick="expand('text1', this);">Click here to hide</div>
<p id="text1" style="display:''; color:blue; background-color:#c1c1c1">
Contents of the p tag</p>

The tag that contains the text shown or hidden must have an id. We set its style display property to 'none'. We pass the tag id to the expand function. The function has two two tag ids as arguments. Only the first one is important here, the second one is just to change the text label. The function gets the style object of the hidden tag,

styleObj=document.getElementById(thistag).style;

and then toggles the display property of the style.

styleObj.display=''; or
styleObj.display='none';

Another tutorial that shows how to create an expandable list using a definition list element is located here .