Most of these solutions are with the assumption you only have one popover/menu/modal at a time. If you have several items, each with its own menu, they won't work without significant modification. My solution is as follows:
document.addEventListener('click', (event) => {
// Check if click done inside popover
const container = event.target.closest('.popover');
// Check if popover open/close button was clicked
const buttonTarget = event.target.dataset.target;
// Ensure all popovers are closed if not requested or clicked inside
for (let popover of document.getElementsByClassName('popover')) {
if (popover.id === buttonTarget && popover.style.display !== `block`) {
popover.style.display = `block`;
} else if (!container) {
popover.style.display = `none`;
}
}
}, false);
Note that the above requires a data-target attribute on the button/input/link set to the modal/popover's id, and a class of popover on all modal/popover items. You can adjust as necessary. You can also dispense with the container check if you want the menu to close as soon as any option has been clicked.
<div onclick="yourFunction()"> </div>