Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  145] [ 1]  / answers: 1 / hits: 16689  / 7 Years ago, tue, june 20, 2017, 12:00:00

I have a bootstrap dropdown menu. I want it to be kept open when I click inside it, but closed when clicking the dropdown toggle button or outside of the menu.


It seems like the dropdown does not close when I type something in the input but it closes when I click anywhere else inside the dropdown.


Q: How can I avoid this by using jQuery?


Below is my HTML:


<div id="navbar">
<nav class="navbar navbar-default navbar-static-top" role="navigation">
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">MENU</a>
<div class="dropdown-menu">
<p>HELLO</p>
<input>
</div>
</li>
</ul>
</div>
</nav>
</div>

Demo in Bootply


More From » jquery

 Answers
26

You can use the following JavaScript to manually open and close the dropdown menu:



$(function() {

$('.dropdown-toggle').on('click', function(event) {
$('.dropdown-menu').slideToggle();
event.stopPropagation();
});

$('.dropdown-menu').on('click', function(event) {
event.stopPropagation();
});

$(window).on('click', function() {
$('.dropdown-menu').slideUp();
});

});


Demo in StackSnippets





$(function() {

$('.dropdown-toggle').on('click', function(event) {
$('.dropdown-menu').slideToggle();
event.stopPropagation();
});

$('.dropdown-menu').on('click', function(event) {
event.stopPropagation();
});

$(window).on('click', function() {
$('.dropdown-menu').slideUp();
});

});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js></script>
<script src=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js></script>
<link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css rel=stylesheet />

<div id=navbar>
<nav class=navbar navbar-default navbar-static-top role=navigation>
<ul class=nav navbar-nav>
<li class=dropdown>
<a href=# class=dropdown-toggle data-toggle=dropdown>MENU</a>
<div class=dropdown-menu>
<p>Hello</p>
<input type=text>
</div>
</li>
</ul>
</nav>
</div>




[#57378] Saturday, June 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
abagail

Total Points: 528
Total Questions: 109
Total Answers: 101

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;