Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make a condition for event 'click' inside/outside for multiple divs - JavaScript?
In JavaScript, you can detect clicks inside or outside multiple divs using event listeners and the contains() method. This is useful for dropdowns, modals, or interactive UI components.
The Problem
When working with multiple divs, you need to determine if a click event occurred inside any of the target divs or outside all of them. This requires checking the event target against all div elements.
Solution Using Event Delegation
Add a single event listener to the document and check if the clicked element is contained within any target div:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Click Inside/Outside Multiple Divs</title>
<style>
.divDemo {
background-color: lightblue;
padding: 20px;
margin: 10px;
border: 2px solid #333;
cursor: pointer;
}
body {
padding: 20px;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h3>Click Inside or Outside the Divs</h3>
<div class="divDemo">
First Division - Click me!
</div>
<div class="divDemo">
Second Division - Click me too!
</div>
<div class="divDemo">
Third Division - Another clickable area
</div>
<p>Click anywhere outside the divs to see the outside click detection.</p>
<script>
document.addEventListener('click', handleClickEvent);
function handleClickEvent(event) {
const targetDivs = document.querySelectorAll('.divDemo');
// Check if click is inside any of the target divs
const clickedInsideDiv = Array.from(targetDivs).find(div =>
div.contains(event.target)
);
if (clickedInsideDiv) {
console.log("Click detected INSIDE a div!");
console.log("Clicked div text:", clickedInsideDiv.textContent.trim());
} else {
console.log("Click detected OUTSIDE all divs!");
}
}
</script>
</body>
</html>
How It Works
The solution uses these key concepts:
- Document Event Listener: Captures all clicks on the page
- querySelectorAll(): Selects all divs with class 'divDemo'
- contains() Method: Checks if the clicked element is inside a div
- Array.from().find(): Searches through divs to find which one contains the click target
Enhanced Version with Click Counters
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Click Counter Inside/Outside Divs</title>
<style>
.divDemo {
background-color: lightgreen;
padding: 15px;
margin: 10px;
border: 2px solid #333;
border-radius: 5px;
}
#counter {
position: fixed;
top: 10px;
right: 10px;
background: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="counter">
<div>Inside clicks: <span id="insideCount">0</span></div>
<div>Outside clicks: <span id="outsideCount">0</span></div>
</div>
<div class="divDemo">Clickable Div 1</div>
<div class="divDemo">Clickable Div 2</div>
<div class="divDemo">Clickable Div 3</div>
<p>Try clicking inside and outside the green divs!</p>
<script>
let insideClicks = 0;
let outsideClicks = 0;
document.addEventListener('click', function(event) {
const targetDivs = document.querySelectorAll('.divDemo');
const counter = document.getElementById('counter');
// Don't count clicks on the counter itself
if (counter.contains(event.target)) {
return;
}
const clickedDiv = Array.from(targetDivs).find(div =>
div.contains(event.target)
);
if (clickedDiv) {
insideClicks++;
document.getElementById('insideCount').textContent = insideClicks;
console.log(`Inside click #${insideClicks}`);
} else {
outsideClicks++;
document.getElementById('outsideCount').textContent = outsideClicks;
console.log(`Outside click #${outsideClicks}`);
}
});
</script>
</body>
</html>
Key Points
- Single Event Listener: More efficient than multiple listeners
- Event Delegation: Handles all clicks from one place
- contains() Method: Reliable way to check element containment
- Array.from(): Converts NodeList to array for using array methods
Common Use Cases
- Closing dropdown menus when clicking outside
- Modal dialog management
- Interactive dashboard components
- Game UI interactions
Conclusion
Use event delegation with document.addEventListener() and the contains() method to efficiently detect clicks inside or outside multiple divs. This approach is scalable and performs well with any number of target elements.
