Created
August 4, 2023 20:00
-
-
Save ihorduchenko/d0f9f103eef2c05e424bc6dc888bf5ef to your computer and use it in GitHub Desktop.
Close dropdown on clicking outside
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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