santa
santa

Reputation: 12512

Progressive reveal with jQuery

I have nested unordered list.

<ul id="catalogue">
    <li>List
        <ul>
            <li>Item 1</li>
            <li>Item 2
                <ul>
                    <li>Item 1.1</li>
                    <li>Item 1.2
                        <ul>
                            <li>Item 1.2.1</li>
                            <li>Item 1.2.2
                                <ul>
                                    <li>Item 1.2.2.1</li>
                                </ul>
                            </li>
                            <li>Item 1.2.3</li>
                        </ul>
                    </li>
                    <li>Item 1.3</li>
                </ul>
            </li>
            <li>Item 3</li>
        </ul>
    </li>
</ul>

At the beginning only the very top level shows, but if you click on each LI, if there's a child UL in it, it should display the next lever, and so on. If you click on the same LI again, the level below should become hidden.

$(document).ready(function () {
    $('#catalogue li').each(function () {
        $(this).contents().first().wrap("<span/>")
    });
    $('#catalogue li > span').addClass('brd');

    $('ul').hide();
    $('#catalogue').show();

    $('#catalogue li').click(function () {
        var nxt = $(this).children('ul:first')
        if ($(nxt).is(":visible")) {
            $(nxt).slideUp();
        } else {
            $(nxt).slideDown();
        }
        $(this).parent().show();
    });

});

If a user clicks on a sibling LI and it has a child UL, that UL should show but any sibling's ones should close.

Upvotes: 0

Views: 274

Answers (1)

PSL
PSL

Reputation: 123739

You need to stop the event from propagating to the parent. Clicking on each li will invoke its own click handler and the event will propagate to its parent li invoke its handler and so on. So you can just stop it at one level by using event.stopPropagation(). And you can use slideToggle to toggle the current state of the element.

Try:

$('#tree li').click(function (e) {
    e.stopPropagation();
    $(this).children('ul:first').slideToggle();
});

Demo

And if you want to slide up while clicked on its sibling then,

$('#tree li').click(function (e) {
    e.stopPropagation();
    var $this = $(this);
    $this.children('ul:first').slideToggle().end()
               .siblings().children('ul:visible').slideUp();
    //Code Broken down
    //$this.children('ul:first').slideToggle();
    //$this.siblings().children('ul:visible').slideUp();
});

Demo

Upvotes: 3

Related Questions