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.
Youve nested double quotes on the a tag!
We corrected the mistake. Thank you;)
Discuss