Reputation: 61105
I have a case where two clicks are required to close a Bootstrap dropdown. I need both to close when a click occurs outside the dropdown, say on another dropdown button.
The same thing probably occurs with a standard select element, but this is my particular scenario. I've tried invoking dropdown('close')
on click of the various Select2 elements with no success.
http://jsfiddle.net/isherwood/PwNpB/15
<div class="dropdown">
<span data-toggle="dropdown" class="btn dropdown-toggle">
Button <span class="caret pull-right"></span>
</span>
<div class="dropdown-menu">
<select id="e1">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
</div>
</div>
Upvotes: 1
Views: 6919
Reputation: 74420
You could use this workaround:
// initialize Select2
$("#e1").select2().on('open', function () {
$('#select2-drop-mask')
.height($(window).height())
.width($(window).width())
.css('opacity', .1);
});
$(document).on('mousedown', '#select2-drop-mask', function () {
$('.dropdown.open').removeClass('open');
});
Upvotes: 4
Reputation: 1436
While I'm not really familiar with either twitter-bootstrap or select2 (and not quite fluent in JavaScript either), I noticed that select2 inserts an element called #select2-drop-mask
which captures the mousedown
- and touchstart
-events and handles the closing of the select2-dropdown:
mask.bind("mousedown touchstart", function (e) {
var dropdown = $("#select2-drop"), self;
if (dropdown.length > 0) {
self=dropdown.data("select2");
if (self.opts.selectOnBlur) {
self.selectHighlighted({noFocus: true});
}
self.close();
}
});
If we attach those same events (a simple click
won't work) to the document
and make sure that the clicked element actually is #select2-drop-mask
(otherwise bootstrap-tooltips 'toggle' would be called twice), things seem to behave like you want them to – the twitter-bootstrap dropdown is closed whenever something outside of the select2-element is clicked:
function closeBootstrapDropdown() {
if ($(event.target).is('#select2-drop-mask')) {
// toggle the twitter-bootstrap dropdown
$('.dropdown.open .dropdown-toggle').dropdown('toggle');
}
}
$(document).on('mousedown touchstart', closeBootstrapDropdown);
Here's a http://jsfiddle.net/PwNpB/3/ – while this seems to work, it still feels slightly dirty to me, so I hope someone with some real understanding of what's happening here and why will chime in.
Upvotes: 3