Some jQuery code not working (.toggle is to blame I think)
I'm following along on O'Reilly's Javascript and Jquery but some code in the book is not working. I've searched the net but haven't came across an obvious answer. Any help would be appreciated.
The HTML is here:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>A One Page Faq</title>
- <link href="../_css/site.css" rel="stylesheet">
- <script src="../_js/jquery-1.7.2.min.js"></script>
- <style type="text/css">
- h2 {
- background: url(../_images/open.png) no-repeat 0 11px;
- padding: 10px 0 0 25px;
- cursor: pointer;
- }
- h2.close {
- background-image: url(../_images/close.png);
- }
- .answer {
- margin-left: 25px;
- }
- </style>
- </head>
- <body>
- <div class="wrapper">
- <div class="header">
- <p class="logo">JavaScript <i>&</i> jQuery <i class="mm">The<br>Missing<br>Manual</i></p>
- </div>
- <div class="content">
- <div class="main">
- <h1>A One Page FAQ</h1>
- <h2>I've heard that JavaScript is the long-lost fountain of youth. Is this true?</h2>
- <div class="answer">
- <p>Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)</p>
- </div>
- <h2>Can JavaScript really solve all of my problems?</h2>
- <div class="answer">
- <p>Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.</p>
- </div>
- <h2>Is there nothing JavaScript <em>can’t</em> do?</h2>
- <div class="answer">
- <p>Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!</p>
- </div>
- </div>
- </div>
- </body>
- </html>
And the script that I wrote is here:
- <script>
- $(document).ready(function() {
- $('.answer').hide();
- $('#main h2').toggle(
- function(){
- $(this).next('.answer').fadeIn();
- $(this).addClass('close');
- },
- function(){
- $(this).next('.answer').fadeOut();
- $(this).removeClass('close');
- }
- );
- }); // end ready
- </script>
If you need any of the other project files, CSS etc. I will happily upload it. I read somewhere online that .toggle is depreciated, but I didn't find any meaningful answers about what to use instead.
Thank you.