Closing section when clicking outside the section (like search bar on this forum)

I want to have a similar search bar like here on this forum. I can let the search field appear thanks to interactions via css class. And it works closing this search field via close button. but how can I close it when clicking outside of the section, where the search field is located in? I tested various JavaScript solutions but nothing seems to work. Anything I am overseeing in bricks to get this done easily?

Thanks to open ai I got the answer, it is a little specific to my site but maybe it helps somebody:

document.addEventListener('mousedown', function (event) {
    const target = event.target;
    const mySearchBarElement = document.querySelector('#brxe-nyaftt[mysearchbar]');
    const searchForm = document.querySelector('.bricks-search-form');

    // If the click was outside the search bar and its children (including the search form), hide the search bar
    if (!mySearchBarElement.contains(target) && !searchForm.contains(target) && mySearchBarElement.getAttribute('mysearchbar') === 'searchbarxy') {
        mySearchBarElement.setAttribute('mysearchbar', '');
    }
});