63 words, 1 min read
    
  
  Sometimes I need to detect whether a click happens inside or outside of a particular element. This is one approach:
window.addEventListener('mousedown', e => {
  // Get the element that was clicked
  const clickedEl = e.target;
  // `el` is the element you're detecting clicks outside of
  if (el.contains(clickedEl)) {
    // Clicked inside of `el`
  } else {
    // Clicked outside of `el`
  }
});
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.
