0

I want to use jQuery to open and close the dropdown. I checked this question, but it is about open only. How to open Bootstrap dropdown programmatically I found these two command to open it and close it.

$('.dropdown-menu').show();
$('.dropdown-menu').close();

However, how can I know the current status of the dropdown? I want click to close if it is open, and click to open if it is close.

chen
  • 69
  • 1
  • 6

2 Answers2

0

You can listen to the event :

// var to be visible in the global scope

var status = false; // default hidden 

$('#myDropdown').on('hidden.bs.dropdown', () => status = false)

$('#myDropdown').on('shown.bs.dropdown', () => status = true)

Later you can check for the status value;

0

If you take a look at the docs, there is one method toggle to do both open and close. As the name suggests, it basically "toggles" between the states.

You use it like:

$('#example').dropdown('toggle');

But I recommend you upgrade to use Bootstrap 4, because this adds loads of new functionality including several new methods for dropdown.

Using the new methods, you can separate the two actions:

$('#example').dropdown('show');
$('#example').dropdown('hide');

To determine the current state in either version, you can utilise the aria-expanded attribute on the dropdown <a> toggle. This attribute changes it's boolean value depending on whether it's open or closed.

You can create an if statement check, something like:

if($("#example .dropdown-toggle[aria-expanded='true'") {
   // dropdown open, so we can close it now.
}
Studocwho
  • 2,404
  • 3
  • 23
  • 29