Javascript Tutorial

Simple Toggle

I've often found myself needing to toggle the visibilty of an element based on a user's action on the page (such as a menu or toolbar item's display). I have found that the easiest way to accomplish this (other than using a library such as jQuery) is to use the following function:

function toggle(id){
	var element = document.getElementById(id);
	if(element.style.display == 'none'){
		element.style.display = 'block';
	}else{
		element.style.display = 'none';
	}
}

This function accepts a single string called "id". It doesn't return any values, but gets the element on the page with the same Id as "id" and then checks the value of the Style attribute's Display for the element. If the element's style.display is currently 'none', the display becomes 'block'. However, if the element's style.display is something other than 'none' id sets it to 'none' and hides the specified element. Below is an example of some HTML that is using this function, and a working example:

<h3 onclick="toggle('element.id');">Header</h3>
<div id="element.id">
	<ul>
		<li>LI 1</li>
		<li>LI 2</li>
	</ul>
</div>

Click Here to Toggle a List...

  • LI 1
  • LI 2