1

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!

Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
John Smith
  • 397
  • 3
  • 5
  • 12
  • 4
    Possible duplicate of [Use jQuery to hide a DIV when the user clicks outside of it](http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it) – p4sh4 Aug 09 '16 at 06:58
  • Possible duplicate of [jquery drop down menu closing by clicking outside](http://stackoverflow.com/questions/6463486/jquery-drop-down-menu-closing-by-clicking-outside) – Pugazh Aug 09 '16 at 07:08
  • Here is an example - https://codepen.io/anon/pen/JKZBdJ – Pugazh Aug 09 '16 at 07:09

1 Answers1

2

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>
vijayP
  • 11,432
  • 5
  • 25
  • 40