I have a custom build modal that has to stop executing any code after it when displayed. For me, this is not a problem when I call it directly (I can handle that) but the problem is when I have to use dispatchEvent on the related element. I've constructed the basic example here:
const modal = document.getElementById("myModal");
const btn = document.getElementById("myBtn");
const span = document.getElementsByClassName("close")[0];
btn.onclick = async function() {
modal.style.display = "block";
return new Promise(resolve => {
span.onclick = async function() {
modal.style.display = "none";
return await true;
};
});
};
(async () => {
btn.style.color = "black";
const event = new Event('click');
await btn.dispatchEvent(event);
btn.style.color = "red";
})();
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<button id="myBtn">Open Modal and wait (Note: this should't be red before closing modal)</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
How can btn.dispatchEvent(event) be awaited?