Detect Click Outside Element JavaScript?: Essential Tips
Image credit: unsplash

Detect Click Outside Element JavaScript: Essential Tips

“Detect Click Outside Element JavaScript” means how we can listen to an event like a click or mouse focus outside of a specific element in JavaScript.

In JavaScript, adding an event listener to a specific element is easy. Once the user interacts with this element, the event is triggered, and we can take our necessary actions accordingly. This is a common scenario.

But sometimes we may want to listen to other elements rather than a specific one before deciding what to do. JS does not provide us with such a specific built-in function to act. So, we have to find alternative ways.

In this scenario, you may think to add an event listener to all other elements except for the element that you want to track. Let’s say you have hundreds or thousands of elements in your HTML document, and you want to add a click event listener to all of them. Is it possible? No, we have to think smartly.


Do it Cleverly in Two Ways:

  1. We can group the elements and just add the event listener to the parent element only. So whenever a user clicks one of the siblings, we can track the event and check the event target to determine which element originated the click event. If it’s an outside element, then we can execute our business logic.
  2. The second option is to add an event listener directly to the HTML body. Once a user clicks on any element within the document, we can check the event target to get the ID of the element. If the element ID is an outside element, then we can execute our business logic.

Code Example to Detect Click outside Element JavaScript

<!DOCTYPE html>
   
   <html>
      <body>
         <div id="div1" style="width: 100%;height: 50px;border:1px solid black;">DIV 1</div>
         <div id="div2" style="width: 100%;height: 50px;border:1px solid black;">DIV 2</div>
      </body>
   </html>

<script>

   document.addEventListener('click', function(event) {
   console.log(event.target);
   
   // Detect Click Outside Element JavaScript
   if(event.target.id !='div2')
      console.log('Outside Click Detected. Take Action Now .....');
   else
      console.log('Inside Click Detected. Do not take any action.');

   });

</script>        

Output: Detect Click Originator using JS

READ MORE >>> Detect Click Outside Element in JS

Khalid Farhan

Building HoverConsole.com | Entrepreneur | Visionary

9 个月

Thanks for sharing

要查看或添加评论,请登录

saion roy的更多文章

社区洞察

其他会员也浏览了