views:

1752

answers:

3

Trying to create collapsible / expandable divs using jQuery, but it's not working for me at all... Each h3 should expand/collapse the div beneath it, and I'm not sure why this isn't working... Granted, is a heavily nested div, but I thought that the script below would find the uforms class regardless of how much other markup is on the page when it loads and then do what it's supposed to do...

Here's the jquery:

$(document).ready(function () {
        $('div.uforms:eq(1)> div:gt(-1)').hide();
        $('div.uforms:eq(1)> h3').click(function() {
                $(this).next('div:hidden').slideDown('fast').siblings('div:visible').slideUp('fast');
        });
});

And, the markup (minus all the stuff that's actually inside the <div></div>, because it's a lot of form stuff...)

<div class="uforms">
  <h3>Heading</h3>
  <div></div>

  <h3>Heading</h3>
  <div></div>

  <h3>Heading</h3>
  <div></div>
</div>
+2  A: 

I think this is what you are trying to achive

I highly recommend the jQueryUI framework.

Ben Shelock
Agreed, no point re-inventing the wheel, just re-use someone else's ;)
wiifm
*Except* if you're not already using jQueryUI, then you're adding a minimum of 32k (using a custom build) just for an accordion.
Justin Johnson
+1  A: 

Checkout video [link below] it has same example that you require

http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/

VAstik
A: 

You're selectors are just wrong. You don't need eq or gt

$(document).ready(function () {
    $('.accordion > div').hide();
    $('.accordion> h3').click(function() {
        $(this).next('div:hidden').slideDown('fast').siblings('div:visible').slideUp('fast');
    });
});

I would change the class identified to something more general so you can reuse this in other places.

<div class="accordion">
    <h3>Heading</h3>
    <div>cactuspants! <div>I am an inner div</div></div>

    <h3>Heading</h3>
    <div>Hats</div>

    <h3>Heading</h3>
    <div>Hi!</div>
</div>

Also, others have suggested that you just use jQueryUI, which is completely valid, unless you're not already using it or intend to use it for additional features. A s3 line function beats including an addition 32K library (the size of the minimally necessary components in a customized build).

Justin Johnson