Code is also available at fiddle. This is a minimal reproducible sample from my project.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button class="alert">Do stuff</button>
</body>
<template id="modal_template">
<div class="modal_background">
<div class="modal_content">
<h2 class="modal_header"></h2>
<p class="modal_message"></p>
<button class="modal_button modal_accept_button"></button>
</div>
</div>
</template>
</html>
async function display_modal(title, message, button_label = "Accept") {
// resolve promise when accept is clicked
return new Promise((resolve) => {
// create a modal from template
const temp = document.querySelector("#modal_template");
let clone = temp.content.cloneNode(true);
clone.querySelector(".modal_header").innerText = title;
clone.querySelector(".modal_message").innerText = message;
// create an accept button
const button = clone.querySelector(".modal_accept_button");
button.innerText = button_label;
button.addEventListener("click", (e) => {
// On click, delete modal and resolve the promise
const modal_background = e.srcElement.parentNode.parentNode;
modal_background.parentNode.removeChild(modal_background);
resolve();
});
document.body.appendChild(clone);
});
}
window.onload = () => {
const alert = document.querySelector(".alert");
alert.addEventListener("click", () => {
display_modal("Alert", "Important message", "Accept").then(console.log("Accept button clicked"));
});
}
Intended behavior
- User clicks on button "Do stuff"
- Modal shows up and gives some buttons for user to click on.
- Button on the modal is clicked.
console.log("Accept button clicked")
is being run and the modal is deleted.
Actual behavior
- User clicks on button "Do stuff".
console.log("Accept button clicked")
has been run. - Modal shows up and gives some buttons for user to click on.
- Button on the modal is clicked.
- the modal is deleted.
current code:
window.onload = () => {
const alert = document.querySelector(".alert");
alert.addEventListener("click", () => {
display_modal("Alert", "Important message", "Accept").then(console.log("Accept button clicked"));
});
}
current behavior feels like:
window.onload = () => {
const alert = document.querySelector(".alert");
alert.addEventListener("click", () => {
display_modal("Alert", "Important message", "Accept");
console.log("Accept button clicked");
});
}
Why does this happen?