I have the following code
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown button <i class="bi bi-x inside-button"></i>
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</div>
<script>
$('.inside-button').on('click', function(e) {
console.log(new Date());
});
</script>
</body>
</html>
As you can see there is a bootstrap icon inside the button dropdown with a click event (by the class inside-button
) the purpose of this functionality is to clear the content of the dropdown.
The problem is the dropdown still open and close when the icon is clicked, the click should only do the action without opening/closing the dropdown, how can I achieve this?
Note: I searched a lot inside stackoverflow before posting, this is for Bootstrap 5.
2
Answers
The easiest way would probably be to move icon element out of the button, so that it doesn’t trigger dropdown, and make dropdown close only from the inside click with
data-bs-auto-close="inside
(drawback is that now the dropdown cannot be closed with outside click…) and then style it with css so that it aligns with the button text and dropdown.The alternative would be to add a lot of JS listeners, which would conditionally trigger dropdown, which is not a good solution.
Here’s a quick-and-dirty example, which
adds
data-bs-auto-close="inside
moves icon out of button as a sibling
adds flex display to their container and centers them
moves icon left to appear inside button
moves button text to span to allow adjusting
">
demo:
You could hide the dropdown when you click on your
inside-button
: