Reputation: 10250
I'm trying to close a Bootstrap 3 dropdown if it's open.
I thought about using $( '#mydropdown' ).dropdown( 'toggle' )
but that doesn't help because if the dropdown is currently closed I don't want it to toggle open.
How can I modify my code so that it checks to see if the dropdown is open before executing the toggle method?
Upvotes: 1
Views: 94
Reputation: 4579
I would suggest use:
$( '#mydropdown.open .dropdown-menu' ).dropdown( 'toggle' )
it simply select dropdown if it is opened and then close it.
Because js add that class to your dropdown element
There is no open / close method in documentation... http://getbootstrap.com/javascript/#dropdowns-usage
Upvotes: 1
Reputation: 406
Can you do a http://jsfiddle.net/?
From bootstrap documentation
Via data attributes or JavaScript, the dropdown plugin toggles hidden content (dropdown menus) by toggling the .open class on the parent list item
Use simple if else to check if the class exists:
if($(".dropdown").hasClass(".open")){
$( '#mydropdown' ).dropdown( 'toggle' );
}
else{
//do nothing
}
Upvotes: 1
Reputation: 10250
if ( $( '#mydropdown' ).hasClass( 'open' ) )
$( '#mydropdown' ).removeClass( 'open' );
This is the solution I went with. It simply removes the .open
class if the dropdown has it.
Upvotes: 1
Reputation: 170
You can trigger the click event manually
$('.navbar').click(); or
$('.navbar').toggle('click');
Upvotes: 0