i am trying to create alert function with div instead of using alert(). The reason why i want to create my own alert function is because i want to have a custom css. Alert function is call within my async call
for e.g [just using dummy code for an example] alert() will actually pause my async call till i click okay which i want
await example.then(dataTable => {
if(condition is true){
alert('this is alert ')
}
)}
now i want to mimic the same functionality with alert function using the method below
html code
<div class="alert_box" id="alert_box" style="visibility:hidden;">
<span class="closebtn" id="closebutton">×</span>
<strong>Error : </strong> Records Exceed 150K Records . Aborting Multi Tab Download
</div>
JavaScript code inside my async call
if(condition is true){
document.getElementById('alert_box').style.visibility = 'visible'
document.getElementById('closebutton').onclick = function(){
console.log("CLICK ME")
document.getElementById('alert_box').style.visibility = 'hidden'
}
I understand that alert is on browser level if im not mistaken but is there a way we can achieve the same result with custom function to mimic alert()?
CSS Style is declared
.alert_box {
padding: 20px;
background-color: #d82b1e;
color: white;
}
.closebtn {
margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
You can pause the function that displays the alert using the Promise API. The idea is to pass the resolve callback to the alert's close button's click handler so it can resolve the promise and resume execution.
Here's a live example:
let resolvePointer;
document.querySelector('#alert_box .closebtn').onclick = function() {
this.closest('#alert_box').style.display = 'none';
if (resolvePointer) resolvePointer();
}
function myAlert(text) {
document.querySelector('#alert_box .text').innerHTML = text;
document.getElementById('alert_box').style.display = 'block';
return new Promise(resolve => {
resolvePointer = resolve;
});
}
async function main() {
// function will pause until alert is dismissed
await myAlert("<strong>Error:</strong> Records Exceed 150K Records. Aborting Multi Tab Download");
console.log("alert dismissed");
}
main();
#alert_box {
display: none;
padding: 20px;
background-color: #d82b1e;
color: white;
}
#alert_box .closebtn {
margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}
#alert_box .closebtn:hover {
color: black;
}
<div id="alert_box">
<span class="closebtn">×</span>
<div class="text"> </div>
</div>