↑
Main Page
Collapsible sections
This example passes the
event
object into the
showTip()
and
hideTip()
methods directly (as discussed
in the previous chapter). When
showTip()
is called,
divTip1
is first made visible by setting
style.
visibility
to
“visible”
. Then, the function moves
divTip1
into position by setting
style.left
and
style.top
equal to
event.clientX
and
event.clientY
. To ensure that the tip doesn’t appear directly
under the cursor, five pixels are added to both the left and top coordinates. The
hideTip()
function sim-
ply sets
style.visibility
back to
“hidden”
so that the tip is no longer visible.
Collapsible sections
Using a similar technique, it’s possible to create collapsible sections on a Web page. This type of func-
tionality has become increasingly popular over the past few years to hide certain settings and fields until
needed. The popularity of this user interface paradigm continues to grow, and it is now added to the
Windows XP file system shell.
The basic idea of collapsible sections is that you can click somewhere to either display or hide a section
of the screen. When one section collapses, all others shift their position to move into the empty space.
Using the CSS
display
attribute can accomplish the same thing. When
display
is set to
none
, the ele-
ment is effectively removed from the flow of the page and the page is redrawn as if the element doesn’t
exist. This is different from setting visibility to
hidden
, which simply hides the element, creating an
empty space where the element resides.
Typically, collapsible sections are arranged into a title bar, which always remains visible, and a content
section, which is expanded or collapsed. To mimic this on the Web, you can use a couple of
<div/>
elements: one for the header and one for the content. You also need a small function to toggle the
expand/collapse of the content. Throw this all together and you get the following example:
<html>
<head>
<title>Style Example</title>
<script type=”text/javascript”>
function toggle(sDivId) {
var oDiv = document.getElementById(sDivId);
oDiv.style.display = (oDiv.style.display == “none”) ? “block” :
“none”;
}
</script>
</head>
<body>
<div style=”background-color: blue; color: white; font-weight: bold;
padding: 10px; cursor: pointer”
onclick=”toggle(‘divContent1’)”>Click Here</div>
<div style=”border: 3px solid blue; height: 100px; padding: 10px”
id=”divContent1”>This is some content
to show and hide.</div>
<p> </p>
<div style=”background-color: blue; color: white; font-weight: bold;
padding: 10px; cursor: pointer”
onclick=”toggle(‘divContent2’)”>Click Here</div>
<div style=”border: 3px solid blue; height: 100px; padding: 10px”
id=”divContent2”>This is some content
to show and hide.</div>
</body>
</html>
308
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 308
Free JavaScript Editor
Ajax Editor
©
→