Close the Bootstrap dropdown by clicking on another dropdown in the same menu?

Asked

Viewed 910 times

4

The menu needs to remain open while I click anywhere on the document or screen, however, when I click on the dropdown of a second menu, it should close the previous one, and also need to open and close by clicking on the dropdown.

My bootstrap code:

 $(function() {
    $('.dropdown.opened')
    .on({
        "shown.bs.dropdown": function() { 
            this.closable = ($('.dropdown.open').length > 1) ? true : false 
         },
        "click":             function() { this.closable = true; 
        if (($('.dropdown.open').length > 1)) {
           $('.dropdown.opened').removeClass('open');
          }

        },
        "hide.bs.dropdown":  function() { return this.closable; }
    });
 });

Note that in the rule I am checking if there is at least 1 open, so it changes the behavior, dropdown, but it should close all menus when I click on any other or the same dropdown, and start the dropdown process again.

View the menu in JSIDDLE

3 answers

1


Already solved the problem, just make a Trigger on the button:

$(function() {
    $('.dropdown.opened')
    .on({
        "shown.bs.dropdown": function() { 
            this.closable = ($('.dropdown.open').length > 1) ? true : false 
         },
        "click":             function() { this.closable = true; 
        $('.dropdown.opened.open').trigger('click');

        },
        "hide.bs.dropdown":  function() { return this.closable; }
    });
 });

0

One solution: Remove the check if (($('.dropdown.open').length > 1))

$(function() {

$('.dropdown.opened')
.on({
    "shown.bs.dropdown": function() { this.closable = ($('.dropdown.open').length > 1) ? true : false },
    "click":             function() { this.closable = true; 
       $('.dropdown.opened').removeClass('open');

    },
    "hide.bs.dropdown":  function() { return this.closable; }
})

});

View the menu in JSIDDLE

  • Follows jsfiddle with your change if you want to add the answer and +1 :)

  • No @Brunno, dropdown is not closing, it does not solve the problem...

  • You just left him stuck... That’s not what I need, I need the menu to be "dropdown", I mean, when I click it first opens and the second time it closes. I edited the question to be clear, okay?

-1

As the removeClass parameter you must pass the opened string. If you remove the open class, it will get stuck. Follow the fiddle:

http://jsfiddle.net/1Lgkbget/6/

(I changed our friend above)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.