How do I detect a click outside an element?

You can listen for a click event on document and then make sure #dropdownmenu is not an ancestor or the target of the clicked element by using .closest().

$(document).click(function(event) { 
  $target = $(event.target);
  if(!$target.closest('#dropdownmenu').length && 
  $('#dropdownmenu').is(":visible")) {
    $('#dropdownmenu').hide();
  }        
});

For those who don’t want to use jQuery. Here’s the above code in plain vanillaJS (ECMAScript6).

function hideOnClickOutside(element) {
    const outsideClickListener = event => {
        if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
          element.style.display = 'none'
          removeClickListener()
        }
    }

    const removeClickListener = () => {
        document.removeEventListener('click', outsideClickListener)
    }

    document.addEventListener('click', outsideClickListener)
}

const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ) // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js

Source: https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element