I have a popup button in my header. I need to make sure that when clicking outside its zone, the popup closes. How can i do this? In the code I'm trying to add remove active classes when clicking on body.active-search but it doesn't work.
const body = document.querySelector("body");
const searchButton = document.querySelector(".search-button");
const searchPopup = document.querySelector(".search-popup");
if (searchButton) {
searchButton.addEventListener("click", () => {
searchPopup.classList.toggle("active");
searchButton.classList.toggle("active");
body.classList.toggle("active-search");
});
}
$(".active-search").click(function() {
searchPopup.removeClass("active");
searchButton.removeClass("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<div class="search-wrapper">
<button class="search-button">Open Search</button>
<div class="search-popup"></div>
</div>
</header>