matt
matt

Reputation: 44373

Make custom dropdown also collapse when clicking the expander?

didn't know how to name this thread:

I build my own little dropdown.

$('.select .option').live('click', function (e) {
    e.stopPropagation();
        $(".select .option:not('.darr')").hide();
        selectedOption = $(this).parents("div.select").find(".option:first");

        $(this).siblings().show();
        selectedOption.text($(this).text()).attr("title",this.title);
});

$('.select .option:not(".darr")').live('click', function () {
    $(this).parents("div.select").find(".option:not('.darr')").hide();
    console.log($(this).attr('data-ajax-link')); 
});

$(window).click(function() {
    $(".select .option:not('.darr')").hide();
});

Here is a working live sample. http://jsfiddle.net/K8VtB/4/

It works just fine. It collapses when clicking anywhere else on the page and when clicking onto another dropdown. However how can I make it also collapse when clicking again onto the first child that initially expanded the dropdown.

Right now when I expand it and click again onto the first element it doesn't collapse again. Any idea how to fix that?

Upvotes: 1

Views: 1411

Answers (2)

gilly3
gilly3

Reputation: 91567

Use .toggle(). I adjusted your code to simplify. The first click handler is for the .darr option. It hides all the selects except itself, and then toggles its options.

The second click handler is for the options. It only set's the text of .darr and lets the click event propagate to the window for closing the selects.

I didn't touch the window click handler.

http://jsfiddle.net/K8VtB/12/

$('.select .option.darr').live('click', function (e) {
    e.stopPropagation();
    $(".select").not($(this).closest(".select")).find(".option:not(.darr)").hide();
    $(this).siblings().toggle();
});

$('.select .option:not(".darr")').live('click', function () {
    $(this).siblings(".darr").text($(this).text()).attr("title",this.title);
});

$(window).click(function() {
    $(".select .option:not('.darr')").hide();
});

Upvotes: 1

Mrchief
Mrchief

Reputation: 76238

Use toggle:

$('.select .option').live('click', function (e) {
    e.stopPropagation();
    // slight optimization, cache the selector for subsequent use
    var $parentDiv = $(this).closest("div.select");  

    // hide other expanders
    $parentDiv.siblings().find(".option:not('.darr')").hide();

    // toggle current expander
    $parentDiv.find(".option:not('.darr')").toggle();

    selectedOption = $parentDiv.find(".option:first");
    selectedOption.text($(this).text()).attr("title",this.title);
});

I also used closest("div.select") to isolate toggling to current ul only.

Here's a working demo: http://jsfiddle.net/mrchief/K8VtB/11/

Update: I missed the part where clicking on other expander hides the previous one. Update my code and fiddle for that.

Upvotes: 2

Related Questions