You are here: Home » Tutorials » Web Development » JavaScript » How to show/hide a DHTML div using onclick() event..

How to show/hide a DHTML div using onclick() event

Added January 24, 2008, read 2451 times

Showing and Hiding a DHTML Div with the onclick() event

Create a simple expandable div with Javascript after reading this tutorial.

HTML Code
<a href="javascript:void(0);"
onclick="ShowHide('divDetails');UpdateText(this);"> // event that triggers the functions
Show Details
</a>
<div id="divDetails" style="display:none;">
Details Panel
</div>
Select all

This block has two sections. The first part of the HTML renders a link on the page that allows the user to click on an element to initiate the change to the style sheet. The next part of the code is the panel that is affected by the change. This is the panel that is hidden from and then displayed again to the user.

JavaScript Code
<script type="text/javascript">

function ShowHide(elementId)
{
	var element = document.getElementById(elementId);
	if(element.style.display != "block")
	{
		element.style.display = "block";
	}
	else
	{
		element.style.display = "none";
	}
}
function UpdateText(element)
{
	if(element.innerHTML.indexOf("Show") != -1)
	{
		element.innerHTML = "Hide Details";
	}
	else
	{
		element.innerHTML = "Show Details";
	}
}

</script>
Select all

The preceding JavaScript changes the web page in two ways. The ShowHide() function does the work of finding the panel on the page, and then updating the style sheet's display property. If the element is not being shown to the user (display:block), then the settings are updated to display the panel. Alternatively, if the panel is being displayed, then the style sheet is updated to hide the panel.

The next function UpdateText() uses the innerHTML property you learned about in the last section, to update the text in the link the user is clicking on. Notice in the HTML that when the function is called, a single argument of this is passed into the function. This element reference allows the function to know which element initiated the call to the function. With this reference, the function examines the innerHTML of the link and makes the appropriate changes to the text displayed to the user.

Discuss

  • Your name
  • Your email (we'll keep this to ourselves)
  • What's it about?
  • Security check

Comments:

this tutorial

posted by Vin on February 08, 2008 at 04:05 AM

Youve nested double quotes on the a tag!

Thank you

posted by Tutorialhelpdesk on May 13, 2008 at 06:44 AM

We corrected the mistake. Thank you;)