0

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!

Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
  • Possible duplicate of [How do I detect a click outside an element?](http://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – Deepak Yadav Apr 10 '17 at 06:57

2 Answers2

1

try

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

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

TorNadO
  • 151
  • 1
  • 6
  • Thank you for your answer, but when I am using this code:- `$('.dropdown-toggle').click(function () { $('.dropdown-menu').slideToggle(); }); $(window).click(function () { $('.dropdown-menu').hide(); });` I am getting my solution but without effect that I want! – Rohit Sharma Apr 10 '17 at 07:23
0

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>
Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
Mihai T
  • 17,254
  • 2
  • 23
  • 32