I have this code:
Full Code: https://codepen.io/anon/pen/wmLBxW
JavaScript code:
function HideOnClickOutside(aContentElement, aFullScreenElement) {
const outsideClickListener = event => {
event.preventDefault();
let isClickInside = aContentElement.contains(event.target);
if (!isClickInside) {
aFullScreenElement.classList.toggle("hidden", true);
removeClickListener();
}
};
const removeClickListener = () => {
document.removeEventListener("click", outsideClickListener);
};
document.addEventListener("click", outsideClickListener);
}
CSS
#fullscreen {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow: auto;
background: black;
opacity: 0.5;
}
.hidden {
display: none;
}
#journal-show-entry {
display: flex;
justify-content: center;
width: 40%;
height: 60%;
border: 1px solid #9b6400;
background-color: #ffffff;
}
HTML
<a href="#" onclick="ShowFullScreenDiv()">Link</a>
<div id="fullscreen" class="hidden">
<div id="journal-show-entry">
</div>
</div>
Which I found in this thread: How do I detect a click outside an element?
However just like in my CodePen, it triggers the outsideClickListener on the same click that adds the EventListener making the div hide itself again on the same click and therefore never shows.
Why is this happening?