score:6

Accepted answer

Add a click listener to document and try to check if it is clicked inside of your container element or outside. If clicked inside, the closest method will return parent container (it will give you the container element), else if clicked out side it will give null. We are interested in null (clicked outside) then we will hide the context menu div

document.addEventListener('click', function(e){
  let inside = (e.target.closest('#container'));
  if(!inside){
    let contextMenu = document.getElementById('contextMenuId');
    contextMenu.setAttribute('style', 'display:none');
  }
});

If you need to set a boundary other than this, just replace #container with anything suitable.

Few browsers don't yet support closest if you are not using jQuery make sure you use the pollyfill for function closest https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

Updated fiddle https://jsfiddle.net/28tvp30b/

NOTE: your container element is almost taking up the whole page its tough to click outside of container. Check if you are actually clicking outside container element.


Related Query

More Query from same tag