detect a click outside an element javascript

JavaScript
$(document).click((event) => {
  if (!$(event.target).closest('#element').length) {
    // the click occured outside '#element'
  }        
});
Source

Also in JavaScript: