Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Hiding and Showing Objects

We will now move on to a number of real-world examples using the DOM objects to manipulate Web pages. As a simple example, you can create a script that hides or shows objects within a page.

As you learned in Hour 18, "Working with Style Sheets," objects have a visibility style property that specifies whether they are currently visible within the page:

Object.style.visibility="hidden"; // hides an object
Object.style.visibility="visible"; // shows an object

Using this property, you can create a script that hides or shows objects in either browser. Listing 20.1 shows the HTML document for a script that allows two headings to be shown or hidden.

Example 20.1. Hiding and Showing Objects

<html>
<head>
<title>Hiding and Showing Objects</title>
<script language="Javascript" type="text/javascript">
function ShowHide() {
   var head1 = document.getElementById("head1");
   var head2 = document.getElementById("head2");
   var showhead1 = document.form1.head1.checked;
   var showhead2 = document.form1.head2.checked;
   head1.style.visibility=(showhead1) ? "visible" : "hidden";
   head2.style.visibility=(showhead2) ? "visible" : "hidden";
}
</script>
</head>
<body>
<h1 ID="head1">This is the first heading</h1>
<h1 ID="head2">This is the second heading</h1>
<p>Using the W3C DOM, you can choose
whether to show or hide the headings on
this page using the checkboxes below.</p>
<form name="form1">
<input type="checkbox" name="head1"
   checked onClick="ShowHide()">
<b>Show first heading</b><br>
<input type="checkbox" name="head2"
   checked onClick="ShowHide()">
<b>Show second heading</b><br>
</form>
</body>
</html>

The <h1> tags in this document define headings with the identifiers head1 and head2. The <form> section defines a form with two check boxes, one for each of the headings. When a check box is modified, the onClick method is used to call the ShowHide function.

This function is defined within the <script> statements in the header. The function assigns the head1 and head2 variables to the objects for the headings, using the getElementById method. Next, it assigns the showhead1 and showhead2 variables to the contents of the check boxes. Finally, the function uses the style.visibility attributes to set the visibility of the headings.

Figure 20.1 shows this example in action in Internet Explorer 6. In the figure, the second heading's check box has been unchecked, so only the first heading is visible.

20fig01.jpg

Figure 20.1 The text hiding/showing example in Internet Explorer.

Share ThisShare This

Informit Network