Easy fix: Just attach a listener to the window triggering an alert
, and another listener on the div that prevents the click event from bubbling up, ensuring it doesn't reach the window.
Note: Using stopPropagation
can be a bit intrusive, but for experimental purposes, it should suffice.
window.onclick = () => alert('hi')
.square{
width: 100px;
height: 100px;
color: red;
background-color: teal;
}
<div onclick="event.stopPropagation()" class="square">TEST</div>
Here's a better solution explaining a more appropriate method for achieving this goal.
Now, adapting that solution to your scenario in a more correct manner, where we analyze the click event to decide whether to trigger the alert
:
const outsideClickListener = element => ({ target }) => {
if (!element.contains(target)) {
alert("hi");
}
};
const squareEl = document.getElementById("square");
document.addEventListener("click", outsideClickListener(squareEl));
#square{
width: 100px;
height: 100px;
color: red;
background-color: teal;
}
<div id="square">TEST</div>
Why avoid using stopPropagation
? In a small project, using it is generally okay (which is why I recommend it). However, in larger real-world projects, it's discouraged as it could disrupt other functionalities. Consider the example below. Developer A added Test 1
expecting alert('hi 1')
to execute whenever the user clicks outside of Test 1
. But then developer B introduced Test 2
with stopPropagation
that halts all events, causing alert('hi 1')
not to run when clicking on Test 2
(outside of
Test 1</code), resulting in a bug.</p>
<p><div>
<div>
<pre class="lang-js"><code>window.onclick = () => alert('hi 2')
const outsideClickListener = element => ({ target }) => {
if (!element.contains(target)) {
alert("hi 1");
}
};
const squareEl = document.getElementsByClassName("square")[0];
document.addEventListener("click", outsideClickListener(squareEl));
.square, .circle {
width: 100px;
height: 100px;
color: red;
background-color: teal;
}
.square {
background-color: teal;
}
.circle {
background-color: wheat;
}
<div class="square">TEST 1</div>
<div onclick="event.stopPropagation()" class="circle">TEST 2</div>