tags:

views:

33

answers:

2

I have headers, and each of those headers has sub items. When I click a header, I want it to toggle viewing or showing the headers contents:

This is what I have so far:

$j('h2').click(function() {
if ($j(this).next().is(":hidden")) {
    $j(this).next().show();
} else {
    $j(this).next().hide();
}
});

And my HTML look like this:

<ul class="submenu">
            <li class="section"><h2>Section One</h2>
                <ul>

                    <li>text</li>


                    <li>text</li>
<li>text</li>

                </ul>
            </li>

            <li class="section"><h2>Section Two</h2>
                <ul style="display: none; overflow-x: visible; overflow-y: visible; ">
<li style="">
                            text</li><li>
                            text</li><li>
                            text</li></ul>
                </li>

        </ul>
A: 

Here is a good tutorial on this subject:

http://homework.nwsnet.de/news/ea21_turn-nested-lists-into-a-collapsible-tree-with-jquery

You will have to tweak it a bit if you want to continue to use the <h2> tags within the lists, but that should be trivial.

W_P
that method seems a bit complex =\
DerNalia
+1  A: 

You can do it the way you have it, or use a slide effect using .slideToggle(), like this:

$('h2').click(function() {
  $(this).next().stop(true, true).slideToggle();
});​

You can test it here

Or instantly without the slide effect using .toggle() (test here):

$('h2').click(function() {
  $(this).next().toggle();
});​

Or a slide + fade effect using .toggle(speed) (test here), like this:

$('h2').click(function() {
    $(this).next().stop(true, true).toggle("fast");
});​

In each case the call to .stop() is to prevent animation queue build-up. This code is for most users where $ == jQuery, it looks like you're using .noConflict() though so just replace $ with $j like your current code has.

Nick Craver
this is great... love that site.. except it isn't working with my copy of jquery / Jqueryui / prototype.. =\ no idea why yet.
DerNalia
I'm using $j but I get this error Uncaught SyntaxError: Unexpected token ILLEGALIt's weird, cause RIGHT above your code, I use the $j thing
DerNalia
and then what is really baffeling, is if i type it out myself, either in the fiddle or in my app, it just doesn't work... no errors though.(this is with the first one, with the link you posted)
DerNalia
@DerNalia - Are you doing this inside a `document.ready` call? Like this: `$(function() { ...the code above... });`?
Nick Craver
No, I was just using the code. =\ does that matteR??
DerNalia
I guess I did need tho $j(functi.... thing...thank you!!!
DerNalia