Skip to content

Instantly share code, notes, and snippets.

@CezaryDanielNowak
Last active September 6, 2019 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CezaryDanielNowak/580c083c7310104ecde607c1119d12d1 to your computer and use it in GitHub Desktop.
Save CezaryDanielNowak/580c083c7310104ecde607c1119d12d1 to your computer and use it in GitHub Desktop.
/**
* This function replaces built-in `confirm` function, but it's async
* Sample usage:
const exitFullscreen = await confirm('Do you really want to exit full-screen mode?');
* @param {String} askText Text to display on the dialog
* @param {Array} buttonText Array with captions of the buttons
* @return {Promise} Resolves with true or false
*/
function confirm(askText = '', buttonText = ['Cancel', 'OK']) {
return new Promise((resolve) => {
const div = document.createElement('div');
div.style.background = '#EEE';
div.style.left = '50%';
div.style.minWidth = '300px';
div.style.padding = '20px';
div.style.position = 'fixed';
div.style.top = '5%';
div.style.transform = 'translateX(-50%)';
div.style.zIndex = 2147483647;
const text = document.createElement('div');
text.innerText = askText;
const buttonCancel = getButtonCancel();
const buttonOK = getButtonOK();
[buttonOK, buttonCancel].forEach((button) => {
button.style.color = '#FFF';
button.style.display = 'inline-block';
button.style.float = 'right';
button.style.fontSize = '20px';
button.style.margin = '10px';
button.style.padding = '5px 10px';
button.type = 'button';
});
div.appendChild(text);
div.appendChild(buttonOK);
div.appendChild(buttonCancel);
document.body.appendChild(div);
function closeDialogAnd(fn) {
return () => {
document.body.removeChild(div);
fn();
};
}
function getButtonOK() {
const btn = document.createElement('button');
btn.style.backgroundColor = '#0095ff';
btn.style.borderColor = '#07c';
btn.style.boxShadow = 'inset 0 1px 0 #66bfff';
btn.innerText = buttonText[1];
btn.onclick = closeDialogAnd(() => resolve(true));
return btn;
}
function getButtonCancel() {
const btn = document.createElement('button');
btn.innerText = buttonText[0];
btn.onclick = closeDialogAnd(() => resolve(false));
btn.style.backgroundColor = '#e23748';
btn.style.borderColor = '#9c1724';
btn.style.boxShadow = 'inset 0 1px 0 #ef9099';
return btn;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment