Essentially, I'm trying to recreate the "alert" and "prompt" functions, but in a single function that uses a modal window. I have it set up so that when one of the function's parameters is set to 1, it adds a text field to the modal window and records that text field's value when it closes. I'm having trouble making it so that when the window is opened, the program waits until the window is closed again. How can I do this?
Asked
Active
Viewed 1,467 times
0
-
Set up the code that displays the modal in a function that returns a Promise. Then have the calling code wait for the Promise to be resolved. – Tangentially Perpendicular Mar 11 '22 at 03:52
-
modal window = HTML DOM or like new browser window? – epascarello Mar 11 '22 at 03:56
-
Please provide enough code so others can better understand or reproduce the problem. – Community Mar 11 '22 at 05:54
1 Answers
2
You need to learn how to use async and await with a promise. Basic idea below showing how the promise is used with the event handler to signal it is clicked.
const myAlert = async(message) => {
return new Promise((resolve) => {
var modal = document.createElement("div");
modal.classList.add("modal");
modal.innerHTML = `
<div class="modal-content">
<span class="close">×</span>
<p>${message}</p>
</div>
`;
modal.querySelector(".close").addEventListener("click", function() {
modal.remove();
resolve();
});
document.body.append(modal);
});
}
(async function() {
console.log('before');
await myAlert('Hello there');
console.log('after');
})();
.modal {
display: block;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%;
/* Could be more or less, depending on screen size */
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}

epascarello
- 204,599
- 20
- 195
- 236