John Smith John Smith - 3 months ago 9
CSS Question

Drop down menu that closes to click elsewhere

I have this sample:



jQuery('.account strong').click(function(e){
jQuery(this).parent('div').addClass('show');
jQuery('.account-dropdown').slideToggle(200);
});

.account-dropdown{
background: #fff;
border-radius: 0 3px 3px 3px;
box-shadow: 2px 3px 7px #555;
display: none;
left: 0;
padding: 10px;
position: absolute;
text-align: left;
top: 46px;
width: 145px;
z-index: 2;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="account">
<strong>Your account</strong>
<div class="account-dropdown">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
</div>





I want to change my script so when you open it, the menu can be closed anywhere.

For example, if the currently open menu closes only if we click on
".account strong '
.

I want the menu to be closed anywhere from less div
'account-dropdown'
.

You can help me solve this problem please?

Thanks in advance!

Answer

You can refer below code:

$('.account strong').click(function(e) {
  $(this).parent('div').addClass('show');
  $('.account-dropdown').slideToggle(200);
  e.stopPropagation();
});

$(document).on('click', function(e) {
  if ($('.account-dropdown').is(":visible")) {
    if ($(e.target).closest(".account-dropdown").length === 0) {
      $('.account-dropdown').slideToggle(200);
    }
  }
});
.account-dropdown {
  background: #fff;
  border-radius: 0 3px 3px 3px;
  box-shadow: 2px 3px 7px #555;
  display: none;
  left: 0;
  padding: 10px;
  position: absolute;
  text-align: left;
  top: 46px;
  width: 145px;
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="account">
  <strong>Your account</strong>
  <div class="account-dropdown">
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
    </ul>
  </div>
</div>

Comments