I'm trying to make a dropdown menu with tabs inside of it. The problem is the dropdown closes when I click a tab. See this demo: http://jsfiddle.net/timrpeterson/pv2Lc/2/. (code reproduced below).
The cited suggestion to stopPropagation()
on the tabs anchors doesn't seem to help. Is there a better way?
<script src='http://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js'></script>
<link href='http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css' rel="stylesheet" type="text/css"/>
<div class="dropdown">
<a id="dLabel" role="button" data-toggle="dropdown" data-target="#" href="/page.html">
Dropdown <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<ul class="nav nav-tabs">
<li class="active"><a href="#home" data-toggle="tab">Home</a> </li>
<li><a href="#profile" data-toggle="tab">Profile</a></li>
<li><a href="#messages" data-toggle="tab">Messages</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">HOME asdfasdfsda</div>
<div class="tab-pane" id="profile">PROFILE asdfafas</div>
<div class="tab-pane" id="messages">MESSAGES asdfdas</div>
</div>
</ul>
</div>
The cited suggestion doesn't work because the .tab('show')
method should be invoked on the actual tab (i.e., the link) instead of the tab pane.
So the code should be:
$('.dropdown-menu a[data-toggle="tab"]').click(function (e) {
e.stopPropagation()
$(this).tab('show')
})
Here is an updated fiddle: http://jsfiddle.net/pv2Lc/6/
Use the specific bootstrap events : the hide.bs.dropdown
(triggered when the dropdown is about to close) allows you to cancel the "hide" action by calling e.preventDefault()
. (doc here, list of specific bootstrap events for scrolldown
components)
You can activate a special flag when the user clicks on a tab, and check that flag in the hide.bs.dropdown
event on the dropdown :
$('#myTabs').on('click', '.nav-tabs a', function(){
// set a special class on the '.dropdown' element
$(this).closest('.dropdown').addClass('dontClose');
})
$('#myDropDown').on('hide.bs.dropdown', function(e) {
if ( $(this).hasClass('dontClose') ){
e.preventDefault();
}
$(this).removeClass('dontClose');
});
fiddle
(I added html ids to your example, change the selectors according to your needs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With