Im using javascript to keep my dropdown toggle on a Bootstrap 4 website not closing when clicking inside the .dropdown element, but I'm having hard time getting it to work so it closes when i click outside the .dropdown element. Currently it doesn't close unless i click the toggle button again...
Any suggestions?
Here is the script
jQuery('.dropdown-toggle').on('click', function (e) {
$(this).next().toggle();
});
jQuery('.dropdown-menu.keep-open').on('click', function (e) {
e.stopPropagation();
});
if(1) {
$('body').attr('tabindex', '0');
}
else {
alertify.confirm().set({'reverseButtons': true});
alertify.prompt().set({'reverseButtons': true});
}
CodePudding user response:
Simply you can add an onclick: event.stopPropagation()
event on the .dropdown-menu
to achieve what you want <div onclick="event.stopPropagation()">
P.S: to use jQuery you can use $
instead of jQuery
. If you cannot use it, you may have jQuery noConflict mode enabled somewhere in your code, see jQuery noConflict
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5 76PVCmYl" crossorigin="anonymous"></script>
<div >
<button type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div onclick="event.stopPropagation()">
<a href="#">Action</a>
<a href="#">Another action</a>
<a href="#">Something else here</a>
</div>
</div>