Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

506 LESSON 18: Using jQuery


<script src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
$("#closed").hide();
$("#open, #closed").click(function (event) {
$("#open, #closed").toggle();
});
});
</script>
</body>
</html>

The page contains two <div>s, one containing the text “We are closed” and one contain-
ing the text “We are open.” In the event handler for the document’s ready state, I hide the
<div>with the ID closed:
$("#closed").hide();
That method sets the display style of the elements matched by the selector to none so
that when the page finishes loadi ng, that <div> will no t be visible, as shown in Figure
18.1.

Then I bind an event handler to the onclick event of those <div>s containing the follow-
ing code:
$("#open, #closed").toggle();
As you can see, this selector matches both the IDs open and closed and calls the
toggle() method on each of them. That method, provided by jQuery, displays hidden
items and hides items that are being displayed. So, clicking the <div> will cause the other
<div>to appear and hide the one you clicked. After you click the <div> and the two
elements have been toggled, the page appears, as shown in Figure 18.2.

FIGURE 18.1
The initial state of
the page. “We are
closed” is hidden.
Free download pdf