Skip to content

Instantly share code, notes, and snippets.

@ashtonmeuser
Created November 19, 2019 00:04
Show Gist options
  • Save ashtonmeuser/1b791575ea256314f095d44f553947d5 to your computer and use it in GitHub Desktop.
Save ashtonmeuser/1b791575ea256314f095d44f553947d5 to your computer and use it in GitHub Desktop.
class Modal {
constructor(message, timeout=3000) {
this.fadeTime = 500;
this.modalBackground = '#f00';
this.present(message);
this.removeTimer = setTimeout(this.remove.bind(this), timeout);
this.fadeTimer = setTimeout(this.fade.bind(this), timeout - this.fadeTime);
}
present(message) {
console.log('present');
this.modal = document.createElement('div');
const modalContent = document.createElement('div');
this.modal.style = `position:fixed; display:flex; width:100%; height:100%; top:0; left:0; z-index:999999; align-items:center; justify-content: center; transition: opacity ${this.fadeTime / 1000}s;`;
modalContent.style = `background-color: ${this.modalBackground};`;
modalContent.innerText = message;
this.modal.appendChild(modalContent);
document.body.appendChild(this.modal);
}
cancel() {
clearTimeout(this.removeTimer);
clearTimeout(this.fadeTimer);
this.remove();
}
fade() {
console.log('fade');
this.modal.style.opacity = 0;
}
remove() {
console.log('remove');
document.body.removeChild(this.modal);
}
}
const singletonModal = (message=Math.random()) => {
if (window.modal instanceof Modal) window.modal.cancel();
window.modal = new Modal(message);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment