jquery - Collapsing / Expanding divs?

n00b0101 picture n00b0101 · Oct 12, 2009 · Viewed 35.1k times · Source

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>

Answer

Justin Johnson picture Justin Johnson · Oct 12, 2009

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).