#development #frontend #javascript #typescript #vuejs
Sometimes I need to detect whether a click happens inside or outside of a particular element. This is one approach:
1window.addEventListener('mousedown', e => {
2 // Get the element that was clicked
3 const clickedEl = e.target;
4
5 // `el` is the element you're detecting clicks outside of
6 if (el.contains(clickedEl)) {
7 // Clicked inside of `el`
8 } else {
9 // Clicked outside of `el`
10 }
11});
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.