The code detects a click outside an element and reloads the page. However, anytime a user clicks outside the page it keeps on reloading the page. How can I reload the page once when the user clicks outside the element?
The reason I want to do this is so when a user inputs text into a form and clicks away the other forms can be rendered with the updated contents. It wouldn't be ideal for the user to click outside the element and the page constantly reloading.
document.addEventListener("click", (evt) => {
const flyoutElement = document.getElementById("flyout-example");
let targetElement = evt.target; // clicked element
do {
if (targetElement == flyoutElement) {
// This is a click inside. Do nothing, just return.
document.getElementById("flyout-debug").textContent = "Clicked inside!";
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// This is a click outside.
document.getElementById("flyout-debug").textContent = "Clicked outside!";
location.reload();
});
body {
font-family: "Arial", sans-serif;
}
h6 {
margin: 0;
font-size: .85rem;
font-weight: normal;
color: #999;
}
.flyout {
position: absolute;
top: 50px;
left: 50px;
padding: 1em;
border: 1px solid rgba(16, 152, 173, .3);
background: white;
box-shadow: 0 .1rem .2rem rgba(0, 0, 0, .15);
}
.flyout-title {
font-size: 1em;
margin: 0 0 .5em 0;
}
.flyout-debug {
min-height: 1.5em;
margin: 0 0 .5em 0;
font-size: .8em;
color: #999;
}
.flyout-buttons {
text-align: center;
}
.button {
display: inline-block;
box-sizing: border-box;
margin: 0 .25em;
padding: .5em 1em;
border: .075rem solid rgba(0, 0, 0, .1);
border-radius: .15em;
background-color: #1098ad;
background-image: linear-gradient(rgba(255, 255, 255, .2), rgba(255, 255, 255, 0));
color: white;
text-decoration: none;
font-family: inherit;
font-size: inherit;
line-height: 1;
box-shadow:
0 .075rem .1rem rgba(0, 0, 0, .15),
inset 0 .075rem rgba(255, 255, 255, .3);
}
.button:hover,
.button:focus {
border-color: rgba(0, 0, 0, .5);
background-image: linear-gradient(rgba(255, 255, 255, .1), rgba(0, 0, 0, .1));
}
.button:active {
background-image: linear-gradient(rgba(0, 0, 0, .1), rgba(0, 0, 0, 0));
box-shadow:
inset 0 .075rem .1rem rgba(0, 0, 0, .2);
}
.button-outline {
background-color: transparent;
background-image: none;
border-color: #1098ad;
color: #1098ad;
box-shadow: none;
}
.button-outline:hover,
.button-outline:focus {
background-color: #1098ad;
background-image: none;
color: white;
}
<div class="flyout" id="flyout-example">
<h5 class="flyout-title">This could be a flyout…</h5>
<div class="flyout-debug" id="flyout-debug"></div>
<div class="flyout-buttons">
<button class="button button-outline" type="button">Cancel</button>
<button class="button" type="button">Ok</button>
</div>
</div>
sessionStoragewhich checks if the outside has been clicked already?