jQuery toggling nested list behaviour – Education Career Blog

I have a number of nested lists and some jQuery that shows hides them when a parent header is clicked.

IT works fine but the behaviour is slightly wrong. If a nested list is visible and the parent header is clicked i would like that nested list to be hidden. At the moment it does this but then shows the nested list directly after.

Please see this jsFiddle for working code:

http://www.jsfiddle.net/4kG2b/

,

Look here:
http://www.jsfiddle.net/dactivo/c3vPa/

We verify if it is visible, and in that case we hide it:

 if( $nestList.is(':visible'))

This would be the code:

 $("#expander ul").hide();
    $("#expander h4").live("click", function(e) {

        var $this = $(this);
        var $nestList = $($this).parent().find("ul");
        var $scrollPane = $(".scroll");

        // hide visible nested lists
        $("#expander ul:visible").hide("fast", function(){
            $(this).closest("li").removeClass("open").addClass("closed");
        });
        // show this list
        if( $nestList.is(':visible'))
        {
          $nestList.hide();   
        }
        else
        {
        $nestList.show("fast", function() {
            $(this).closest("li").removeClass("closed").addClass("open");
        });
        }
        // resize scrollbars
        $scrollPane.jScrollPane();

        e.preventDefault();
    });

,

You can trigger the show if the sibling <ul> is hidden currently (effectively making it a toggle), like this:

    $nestList.filter(":hidden").show("fast", function() {
        $(this).closest("li").removeClass("closed").addClass("open");
    });

You can test it out here. Overall you can slim it down and get the same effect though, like this:

$("#expander ul").hide();
$("#expander h4").live("click", function() {
    $(this).siblings("ul").toggle("fast", function(){
        $(this).closest("li").toggleClass("open closed");
    }).closest("li").siblings(".open").toggleClass("open closed")
                    .children("ul").hide("fast");

    $(".scroll").jScrollPane();
});

You can try that version out here.

Leave a Comment