02.06.2013 Views

JavaScript & jQuery: The Missing Manual ... - Robert Guajardo

JavaScript & jQuery: The Missing Manual ... - Robert Guajardo

JavaScript & jQuery: The Missing Manual ... - Robert Guajardo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

9 function() {<br />

10 $(this).next('.answer').fadeOut();<br />

11 }<br />

12 ); // end of toggle()<br />

13 }); // end of ready()<br />

14 <br />

Now the answer fades out on a second click. Save the page and give it a try.<br />

While the page functions fine, there’s one nice design touch you can add. Currently,<br />

each question has a small plus sign to the left of it. <strong>The</strong> plus sign is a<br />

common icon used to mean, “Hey, there’s more here.” To indicate that a visitor<br />

can click to hide the answer, replace the plus sign with a minus sign. You can do<br />

it easily by just adding and removing classes from the tags.<br />

9. Add two final lines of code (lines 8 and 12 below). <strong>The</strong> finished code should<br />

look like this:<br />

1 <br />

2 <br />

3 $(document).ready(function() {<br />

4 $('.answer').hide();<br />

5 $('#main h2').toggle(<br />

6 function() {<br />

7 $(this).next('.answer').fadeIn();<br />

8 $(this).addClass('close');<br />

9 },<br />

10 function() {<br />

11 $(this).next('.answer').fadeOut();<br />

12 $(this).removeClass('close');<br />

13 }<br />

15 ); //end toggle<br />

15 });<br />

16 <br />

This code simply adds a class named close to the tag when it’s clicked the<br />

first time, then removes that class when it’s clicked a second time. <strong>The</strong> minus<br />

sign icon is defined within the style sheet as a background image. (Once again,<br />

CSS makes <strong>JavaScript</strong> programming easier.)<br />

Save the page and try it out. Now when you click a question, not only does the<br />

answer appear, but the question icon changes (see Figure 5-6).<br />

chapter 5: action/reaction: making pages come alive with events<br />

www.it-ebooks.info<br />

Tutorial: A One-<br />

Page FAQ<br />

183

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!