Simple solution: Add a listener to the window that produces the alert
and add a listener to the div that stops the click event from propagating so that it never reaches the window.
Disclaimer: calling stopPropagation
is not a great thing to do as it's quite intrusive, but I'm guessing you're just trying things out, so it should be fine.
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 good answer that describes a more proper way to achieve this.
And here's that answer adjusted to your case in a more correct solution where we look at the click event to determine if we should call 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 should we not use stopPropagation
? In a small project there's not a big problem to use it (which is why it's my top recommendation). But in a big real world project it's ill advice, because it can break behavior of other stuff. See below example. Developer A added Test 1
and expects alert('hi 1')
to be ran every time the user clicks outside of Test 1
. But developer B added Test 2
which calls stopPropagation
that stops all events, so when the user clicks Test 2
(which is outside of Test 1
) alert('hi 1')
is not ran and we have a bug.
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>