<button id="trigger">Open Modal</button>
<div id="modal" class="modal-wrapper">
<div class="modal-backdrop"></div>
<div class="modal-content">
<span>Clicking anywhere in the white area doesn't close the modal. Try it!</span>
<button id="closeBtn">Close Me</button>
</div>
</div>
.modal-wrapper {
visibility: hidden;
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: gray;
opacity: 0.75;
}
.modal-content {
/* Positioning */
position: absolute;
top: 25vh;
left: 25vw;
/* Sizing and color */
min-width: 50vw;
min-height: 50vh;
background: white;
/* Beautifying */
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
}
.modal-content button {
width: 5rem;
height: 2rem;
}
.modal-content span {
margin: 0 1rem;
}
const triggerBtn = document.getElementById("trigger");
const modal = document.getElementById("modal");
const modalContent = document.querySelector(".modal-content");
const closeBtn = document.getElementById("closeBtn");
triggerBtn.addEventListener("click", e => {
e.stopPropagation();
addAutocloseEvents();
modal.style.visibility = "visible";
});
closeBtn.addEventListener("click", () => {
closeModal();
removeAutocloseEvents();
});
const addAutocloseEvents = () => {
document.addEventListener("click", handleDocumentClick);
document.addEventListener("keyup", handleDocumentKeyup);
};
const removeAutocloseEvents = () => {
document.removeEventListener("click", handleDocumentClick);
document.removeEventListener("keyup", handleDocumentKeyup);
};
const handleDocumentClick = evt => {
if (!modalContent.contains(evt.target)) {
closeModal();
}
};
const handleDocumentKeyup = evt => {
if (evt.key === "Escape") {
closeModal();
}
};
const closeModal = () => (modal.style.visibility = "");
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.