I have a button dropdown (just one, not all of them), and inside of it, I want to have several input field where people can type stuff inside without the dropdown hiding as
Actually, if you were in Angular.js, it would be more elegant to make a directive for it:
app.directive('stopClickPropagation', function() {
return {
restrict: 'A',
link: function(scope, element) {
element.click(function(e) {
e.stopPropagation();
});
}
};
});
And then, on the dropdown-menu, add the directive:
<div class="dropdown-menu" stop-click-propagation>
my dropdown content...
<div>
Especially if you want to stop propagation for multiple mouse events:
...
element.click(function(e) {
e.stopPropagation();
});
element.mousedown(...
element.mouseup(...
...
also, prevent click unless clicks a button element
$('.dropdown-menu').click(function(e) {
if (e.target.nodeName !== 'BUTTON') e.stopPropagation();
});
The issue is that the boostrap dropdown jQuery plugin closes the dropped-menu when you click anywhere else. You can disable that behavior by capturing the click events on your dropdown-menu element and keeping it from reaching the click event listeners on the body element.
Just add
$('.dropdown-menu').click(function(event){
event.stopPropagation();
});
jsfiddle can be found here
I know this question isn't for Angular per se, but for anyone using Angular you can pass the event from the HTML and stop propagation via $event:
<div ng-click="$event.stopPropagation();">
<span>Content example</span>
</div>
After trying a lot of techniques I found that the best one to use, that causes no drawbacks which is even simple:
$(document)
.on( 'click', '.dropdown-menu', function (e){
e.stopPropagation();
});
Which lets you also do some live binding for inner elements inside dropdowns.
Another quick solution, just add onclick
attribute to div having class dropdown-menu
:
<div class="dropdown-menu" onClick="event.stopPropagation();">...</div>