Home > Articles

  • Print
  • + Share This
This chapter is from the book

Hiding and Showing Objects

In the preceding example, you saw some functions that could be used to hide or show the “square.” In this section, we’ll take a closer look at hiding and showing objects within a page.

As a refresher, 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 6.7 shows the HTML document for a script that allows two headings to be shown or hidden.

LISTING 6.7 Hiding and Showing Objects

<!DOCTYPE html>

<html lang="en">
  <head>
    <title>Hiding or Showing Objects</title>
    <script type="text/javascript">
    function showHide() {
       if (!document.getElementById) return;
       var heading1 = document.getElementById("heading1");
       var heading2 = document.getElementById("heading2");
       var showheading1 = document.checkboxform.checkbox1.checked;
       var showheading2 = document.checkboxform.checkbox2.checked;
       heading1.style.visibility=(showheading1) ? "visible" : "hidden";
       heading2.style.visibility=(showheading2) ? "visible" : "hidden";
    }
    </script>
  </head>
  <body>
     <h1 id="heading1">This is the first heading</h1>
     <h1 id="heading2">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="checkboxform">
     <input type="checkbox" name="checkbox1"
            onclick="showHide();" checked="checked" />
     <span style="font-weight:bold">Show first heading</span><br>
     <input type="checkbox" name="checkbox2"
           onclick="showHide();" checked="checked" />
     <span style="font-weight:bold">Show second heading</span><br>
     </form>
  </body>
</html>

The <h1> tags in this document define headings with IDs of head1 and head2. Inside the <form> element are two check boxes, one for each of these headings. When a check box is modified (checked or unchecked), the onclick method calls the JavaScript showHide() function to perform an action.

The showHide() function is defined within the <script> tag in the header. This function assigns the objects for the two headings to two variables named heading1 and heading2, using the getElementById() method. Next, it assigns the value of the check boxes within the form to the showheading1 and showheading2 variables. Finally, the function uses the style.visibility attributes to set the visibility of the headings.

TIP

Figure 6.8 shows this example in action. In the figure, the first heading’s check box has been unchecked, so only the second heading is visible.

FIGURE 6.8

FIGURE 6.8 The text-hiding/showing example in action.

  • + Share This
  • 🔖 Save To Your Account