ptg16476052
538 LESSON 19: Using JavaScript in Your Pages
▼
Hiding and Showing Content
One way to help users deal with a lot of information presented on a single page is to hide
some of it when the page loads and to provide controls to let them view the information
that interests them. In this example, I create a frequently asked questions page. On this
page, the questions will be organized in sections. Each section will start out collapsed,
and the answers to the questions will be hidden as well. Users can display the answers by
clicking the corresponding questions.
In this example, I apply an approach referred to as unobtrusive JavaScript. The phi-
losophy behind it is that the behavior added by JavaScript should be clearly separated
from the presentation applied using HTML and Cascading Style Sheets (CSS). The page
should work and be presentable without JavaScript, and JavaScript code should not be
mixed with the markup on the page.
In practice, what this means is that event handlers should be specified in scripts instead
of HTML attributes. Also, in this example, using JavaScript unobtrusively means that if
the user has JavaScript turned off, she will see all the questions and answers by default,
rather than seeing a page with the questions hidden and no means of displaying them.
In the previous lesson, you learned how to hide and show content using jQuery. In this
example, I’m going to explain how to accomplish the same thing using plain JavaScript,
and then provide the jQuery version as a comparison. jQuery is a convenience, but it’s
not necessary for building things with JavaScript, as you’ll see.
Exercise 19.2: Hiding and Showing Content
The exercise starts with a web page that doesn't include JavaScript and that displays the
frequently asked questions. Here’s the source for the page. Figure 19.6 shows the page in
a browser.
Input ▼
<!DOCTYPE html>
<html>
<head>
<title>Frequently Asked Questions</title>
<style type="text/css" media="screen">
dt { margin-bottom: .5em; font-size: 125%;}
dd { margin-bottom: 1em;}
</style>
</head>
<body>
▼<h1>Frequently Asked Questions</h1>