Rohit Sharma
Rohit Sharma

Reputation: 3334

Hide dropdown list when clicking outside the button

I am using a bootstrap dropdown list but I have attached my own jQuery in it. My code is here

<button class="btn dropdown-toggle" type="button" data-toggle="dropdown">User Name<span class="caret"></span></button>
<ul class="dropdown-menu">
  <li><a href="#">Profile</a></li>
  <li><a href="#">Logout</a></li>
</ul>
$('.dropdown-toggle').click(function () {
  $('.dropdown-menu').slideToggle();
});

When I am not using jQuery, dropdown is being hidden on clicking outside the button (anywhere in body). But after using slideToggle function it's not being hide. I want the same effect as slideToggle() function to hide dropdown!

Upvotes: 0

Views: 315

Answers (2)

Mihai T
Mihai T

Reputation: 17687

if i understand you right, you want when click on anywhere on body ( except the button or the dropdown ) the dropdown to slideUp again. you can use this code below.

let me know it helps

see snippet or fiddle > jsfiddle

$('.dropdown-toggle').click(function() {
  $('.dropdown-menu').slideToggle();
});
$(document).mouseup(function(e) {
  if (!$(".dropdown-menu").is(e.target) &&
    !$(".dropdown-toggle").is(e.target) &&
    $(".dropdown-menu").has(e.target).length === 0 &&
    $(".dropdown-toggle").has(e.target).length === 0) {
    $(".dropdown-menu").slideUp()
  }
});
section {
  position: relative
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

<section>
  <button class="btn dropdown-toggle" type="button" data-toggle="dropdown">User Name<span class="caret"></span></button>
  <ul class="dropdown-menu">
    <li><a href="#">Profile</a></li>
    <li><a href="#">Logout</a></li>
  </ul>
</section>

Upvotes: 0

TorNadO
TorNadO

Reputation: 151

try

...click(function(e){
 e.stopPropagation();
 ...
});

This will reduce possible observation of the click's propagation through layered HTML elements

Upvotes: 1

Related Questions