views:

146

answers:

1

I have a semi-working example that you can look at.

This appears to work as most would desire, though it shares a bug I am seeing in many other accordions, which is if you click on the an already opened header link, it will be closed, and then opened again.

Any elegant solutions?

Here is the jQuery

 <script language="javascript">
      $(document).ready(function() {

        // Simple Accordion Style Menu Function
        $('h2.question').click(function() {
         $('div.answer').slideUp('normal'); 
         $(this).next().slideDown('normal');
        });

        // Closes All Divs on Page Load
        $("div.answer").hide();

        // Opens the first div
        var Current = $('.question:first');
           Current.next().show();

      });
 </script>

And here is the basic markup I am looking to use:

 <div class="accordion">
      <h2 class="question"><a href="#">Header 1</a></h2>
      <div class="answer">
           <p>some body content 1</p>
           <p>some body content 2</p>
           <p>some body content 3</p>
      </div>

      <h2 class="question"><a href="#">Header 2</a></h2>
      <div class="answer">
           <p>some body content a</p>
           <p>some body content b</p>
           <p>some body content c</p>
      </div>

      <h2 class="question"><a href="#">Header 3</a></h2>
      <div class="answer">
           <p>some body content x</p>
           <p>some body content y</p>
           <p>some body content z</p>
      </div>
 </div>
+2  A: 

You could try adding a class on the h2 to note its active then check for that on each h2 click? If it has the active class on it then do nothing as it is already open. Also on page load it gives the first h2.question a class of active.

<script language="javascript">
      $(function() {
            // Simple Accordian Style Menu Function
            $('h2.question').click(function() {
              if(!$(this).hasClass('active')) {
                $('div.answer:visible').slideUp('normal').prev('h2.question').removeClass('active');
                $(this).addClass('active').next().slideDown('normal');
              }
            });

            // Closes All Divs on Page Load
            $("div.answer").hide();

            // Opens the first div
            var Current = $('h2.question:first');
               Current.addClass('active').next().show();

          });
     </script>
Colin
Very nice, I was playing around with testing it's visibility state, which seemed a little rigged. This works well, thank you.