The other solutions here didn't work for me so I had to use:
if(!$(event.target).is('#foo'))
{
// hide menu
}
Edit: Plain Javascript variant (2021-03-31)
I used this method to handle closing a drop down menu when clicking outside of it.
First, I created a custom class name for all the elements of the component. This class name will be added to all elements that make up the menu widget.
const className = `dropdown-${Date.now()}-${Math.random() * 100}`;
I create a function to check for clicks and the class name of the clicked element. If clicked element does not contain the custom class name I generated above, it should set the show flag to false and the menu will close.
const onClickOutside = (e) => {
if (!e.target.className.includes(className)) {
show = false;
}
};
Then I attached the click handler to the window object.
// add when widget loads
window.addEventListener("click", onClickOutside);
... and finally some housekeeping
// remove listener when destroying the widget
window.removeEventListener("click", onClickOutside);