Skip to content

Instantly share code, notes, and snippets.

@dwerbam
Created December 23, 2021 09:31
Show Gist options
  • Save dwerbam/41814eec91f7c4427354de23b4d6485f to your computer and use it in GitHub Desktop.
Save dwerbam/41814eec91f7c4427354de23b4d6485f to your computer and use it in GitHub Desktop.
creating modal popups in javascript and keeping async/await thread
const modalWaitElem = async selector => {
while ( document.querySelector(selector) !== null) {
await new Promise( _ => setTimeout(_, 500) )
// // faster than setTimeout (not needed)
// await new Promise( _ => requestAnimationFrame(_) )
}
return document.querySelector(selector)
};
async function createVisualElement(parent, className) {
const popup = document.createElement("div")
popup.classList.add(className)
// set max dimensions
popup.style.width = "100%"
popup.style.height = "100%"
// white background with opacity
popup.style.backgroundColor = "darkgrey"
popup.style.opacity = "0.8"
// overlap with the body
popup.style.position = "absolute";
popup.style.zIndex = parent.style.zIndex > 1000? parent.style.zIndex + 1 : 1000;
// paint something
const some = document.createElement("div")
some.style.backgroundColor = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
some.style.left = `${Math.round(Math.random() * 10)}px`;
some.style.top = `${Math.round(Math.random() * 10)}px`;
some.style.width = `${Math.round(Math.random() * 1200)}px`;
some.style.height = `${Math.round(Math.random() * 1200)}px`;
some.style.border = "solid black 3px"
popup.appendChild(some)
// insert as first element
parent.insertBefore(popup, parent.firstChild)
return popup;
}
async function openModal(modalParent, modalClassName, resultAttribute = "modal-result") {
console.log("openModal", modalClassName)
// creates modal popup with .popup class
const popup = await createVisualElement(modalParent, modalClassName)
popup.addEventListener("click", async (event) => {
event.stopPropagation()
if (event.shiftKey) {
modalParent.setAttribute(resultAttribute, event.altKey? "accepted" : "cancelled")
popup.remove()
} else {
// generates a random modalClassName
var childClassName = `modalPopup-${Math.round(Math.random() * 100000)}`;
var x = await openModal(popup, childClassName, resultAttribute)
console.log("child result", x)
}
})
await modalWaitElem(`.${modalClassName}`)
// get the result
console.log("modal removed!")
return modalParent.getAttribute(resultAttribute)
}
async function main() {
console.log("starting main..")
var x = await openModal( document.querySelector("body"), "modalPopup")
console.log("done main!", x)
}
await main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment