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:
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
Building HoverConsole.com | Entrepreneur | Visionary
9 个月Thanks for sharing