jQuery hide on body click

[/iframe]

html:

<div class="js-list-wrap">
  <button class="js-list-btn">
  Click
  </button>
  <div class="js-list-content hidden">
  List item 1<br>
  List item 2
  </div>
</div>

javascript:

$('.js-list-btn').click(function(e) {
    e.stopPropagation();
    $(this).closest('.js-list-wrap').find('.js-list-content').toggleClass('hidden');
});
 
$('.js-list-content').click(function (e) { // keep list visible while clicking inside of the list dropdown
    e.stopPropagation();
});
 
$('body').click(function (e) { // hide list dropdown on body click
    $('.js-list-content').addClass('hidden');
});

css:

.js-list-wrap {
  position: relative;
}
 
.js-list-content {
  position: absolute;
  left: 0;
  top: 15px;
  background: #eee;
  display: inline-block;
}
 
.hidden {
  display: none;
}

Leave a Reply

Your email address will not be published. Required fields are marked *