Skip to content

Instantly share code, notes, and snippets.

@ihorduchenko
Created August 4, 2023 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ihorduchenko/d0f9f103eef2c05e424bc6dc888bf5ef to your computer and use it in GitHub Desktop.
Save ihorduchenko/d0f9f103eef2c05e424bc6dc888bf5ef to your computer and use it in GitHub Desktop.
Close dropdown on clicking outside
<fieldset class="filtersDropdown">
<div class="filtersDropdownTrigger">
Dropdown trigger
<div class="caret pointer-events-none">
<svg class="pointer-events-none"><use xlink:href="#icon-angle-down"></use></svg>
</div>
</div>
<div class="dropdown-body"></div>
</fieldset>
<script>
var filtersDropdown = $('.filtersDropdown');
filtersDropdown.each(function() {
let $this = $(this);
let trigger = $this.find('.filtersDropdownTrigger');
document.addEventListener('click', (event) => {
let withinBoundaries = event.composedPath().includes($this[0]);
if (withinBoundaries) {
if (event.target == trigger[0] && $this.hasClass('is-open')) {
$this.removeClass('is-open');
} else {
$this.addClass('is-open');
}
} else {
$this.removeClass('is-open');
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment