sqe
sqe

Reputation: 1716

jQuery slideToggle li when clicking another li

I want to close (slideToggle) a listelement with an nested ul and li in it when clicking on another listelement with an nested ul and li in it.

This is my jQuery for the toggle itself:

$(document).ready(function () {
    $("ul > li.closed").click(function (e) {
        if (e.target === this) {
            var li = $(this).closest('li');
            li.find(' > ul').slideToggle('fast');
            $(this).toggleClass("closed open");
        }
    });
});

On my fiddle: I want to close the "Topic 1" when clicking on "Topic 2". And I want to close "Subtopic 1" when clicking on another "Subtopic x".

FIDDLE

Upvotes: 0

Views: 1049

Answers (1)

mohsen dorparasti
mohsen dorparasti

Reputation: 8415

I suggest you to first close all open lists then open clicked one :

remove rules in li.closed > ul

li.closed > ul {

}

because display:none conflicts with slideToggle() when you click twice on the same li

and change the script to

$(document).ready(function () {    
    $("#nav li ul").css('display','none');
    $("ul > li.closed").click(function (e) {
        if (e.target === this) {
            $(this).siblings("li.open").find(" > ul").slideToggle('fast',function(){
                $(this).parents("li.open:first").toggleClass("open closed");   
            });

            $(this).toggleClass("closed open").find(" > ul").slideToggle('fast');
        }
    });
});

Upvotes: 1

Related Questions