I cannot Close the dropdown using the button but i can close it when I clicked the outer page.
var $menu = $('.menu');
$('.toggle').click(function () {
$menu.toggle();
});
$(document).mouseup(function (e) {
if (!$menu.is(e.target) // if the target of the click isn't the container...
&& $menu.has(e.target).length === 0) // ... nor a descendant of the container
{
$menu.hide();
}
});
Please help me guys.
$(document).ready(function(){ var $menu = $('.menu'); $('.toggle').click(function (e) { e.stopPropagation(); $menu.toggle(); }); $('.container').click(function (e) { e.stopPropagation(); $menu.toggle(); }); });
.dropdown { margin: 200px auto; position: relative; width: 50%; } .toggle, .dropdown-menu { width: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div class="row"> <div class="text-center col-xs-12"> <h1>jQuery: click outside to close menu</h1> <p>Click the button to toggle the dropodown menu.</p> <p>Then click outside dropdown menu to close.</p> <div class="dropdown"> <a href="#" title="" class="btn btn-default toggle">Toggle menu</a> <ul class="dropdown-menu menu"> <li class="dropdown-item">List item 1</li> <li class="dropdown-item">List item 2</li> <li class="dropdown-item">List item 3</li> </div> </div> </div> </div>
Use event.stopPropagation();
this will not prevent other handlers on the same element from running.
Simply U need only one action on mouse click. Your JS must be:
var $menu = $('.menu');
var $toggle = $('.toggle');
$(document).mouseup(function (e) {
if ($toggle.is(e.target)) {
$menu.toggle()
} else {
$menu.hide();
}
});
If you want to open and close on button. Just remove the second function and your code will work.
var $menu = $('.menu');
$('.toggle').click(function () {
$menu.toggle();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.