I was creating a dialog to confirm action by user.
We can achieve that by confirm() dialog like this:
function btnChangeBodyColorFunc() {
let text = "You are going to change body color.Are you sure";
if (confirm(text) == true) {
document.body.style.backgroundColor = "red";
console.log("You changed!");
} else {
document.body.style.backgroundColor = "";
console.log("You canceled!");
}
}
<button onclick="btnChangeBodyColorFunc()">Change body color to red</button>
But can it be sort of custom like this:
let iConfirmToGoAhead = ""
let confirmDialog = document.querySelector(".confirmDialog");
function btnChangeBodyColorFunc() {
confirmDialog.style.display = "flex";
if (iConfirmToGoAhead === "true") {
document.body.style.backgroundColor = "red";
console.log("You changed!");
iConfirmToGoAhead = ""
} else if (iConfirmToGoAhead === "false") {
document.body.style.backgroundColor = "";
console.log("You canceled!");
iConfirmToGoAhead = ""
}
}
let confirmDialogBtn = document.querySelectorAll(".confirmDialogContent button");
for (let i = 0; i < confirmDialogBtn.length; i++) {
confirmDialogBtn[i].addEventListener('click', confirmDialogBtnFunc)
}
function confirmDialogBtnFunc() {
confirmDialog.style.display = "none";
iConfirmToGoAhead = this.dataset.confirmationValue;
}
.confirmDialog {
position: fixed;
display: none;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.7);
height: 100vh;
width: 100vw;
}
.confirmDialogContent {
margin: auto;
}
<button onclick="btnChangeBodyColorFunc()">Change body color to red</button>
<div class="confirmDialog">
<div class="confirmDialogContent">
You are going to change body color.Are you sure
<button data-confirmation-value="true">Yes sure</button>
<button data-confirmation-value="false">No don't change</button>
</div>
</div>
But this way it don't wait for iConfirmToGoAhead value to be confirmed and execute the function.
Know this is how JS works that execute the codes which comes first. I tried use of async and await but that also don't work and throw error(might not applied it right).
Can do required functionality by adding conditions to second function but thought a common way for all critical actions through 1 dialog and change according to it.
Is it possible to have a custom confirmation dialog like this or have to use conditions in 2nd function. Any ideas are most welcome
Thanks for help in advance