jQuery: Expand only one panel at a time

61
November 21, 2016, at 9:51 PM

Inside each <li> when <i> is clicked it expands and collapses the <ul> that follows. Need to make it so that once another <i> is clicked it collapses the previous <ul>.

See my fiddle

<ul class="nav-main">
    <li> <a href="/en/courses">Courses</a><i class="expand closed"></i>
        <ul class="drop">
            <li><a href="#">Campuses</a>
            </li>
            <li><a href="#">Online Learning</a>
            </li>
            <li><a href="#">Start dates and schedules</a>
            </li>
            <li><a href="#">Learning and Support</a>
            </li>
        </ul>
    </li>
    <li> <a href="#">Outcomes</a><i class="expand closed"></i>
        <ul class="drop">
            <li><a href="#">Career Starter Program</a>
            </li>
            <li><a href="#">Progress to a degree</a>
            </li>
            <li><a href="#">Career Pathways</a>
            </li>
        </ul>
    </li>
</ul>
Answer 1

You will want to loop through each panel and ensure it is closed whenever an item is clicked, closing any that are not the item clicked. Here's your fiddle updated: https://jsfiddle.net/zb2eu19g/8/

The relevant JS code:

// Main Menu Slider
$('.nav-main .expand').on('click', function (e) {
    var clickedPanel = this;
    $('.nav-main .expand').each(function() {
        if (this !== clickedPanel && !$(this).hasClass('closed')) {
            $(this).addClass('closed').next('ul').slideUp(300, function () {
                $(this).removeAttr('style');
            });
        }
    });
    if ($(this).hasClass('closed')) {
        $(this).removeClass('closed').next('ul').slideDown(300);
    } else {
        $(this).addClass('closed').next('ul').slideUp(300, function () {
            $(this).removeAttr('style');
        });
    }
    e.preventDefault();
});

If it was me, I'd extract out the logic to open and close items into functions to get rid of some of the duplication here, but this gives you a start.

READ ALSO
Why aren&#39;t these buttons deleting the rows that contain them?

Why aren't these buttons deleting the rows that contain them?

What I'm trying to do with the following snippet should be self-explanatory.

41
read an JSON object with javascript

read an JSON object with javascript

so i have a question, i have a json object, but i cant read with javascript.

73