Javascript Popups and Promises

https://www.lateral.co.za/writing/popups-and-promises for a full description.

by Craig Mason-Jones

HTML

<button id="showPopup">Show the popup</button>

<div id="html_confirm">
	<div>
		<div class="titlebar">Confirm</div>
		<div class="content">
			Our message will go here.
		</div>
		<div class="buttons">
			<button class="button-cancel">No</button>
			<button class="button-continue">Yes</button>
		</div>
	</div>
</div>

CSS

#html_confirm {
  position: absolute;
  margin: 0;
  padding: 0;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;

  display: none;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  background-color: rgba(0, 0, 0, 0.7);
}

#html_confirm.showing {
  display: flex;
}

#html_confirm>div {
  background-color: white;
  padding: 1em;
  border: 1px solid #ccc;

  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  gap: 0.6em;
}

#html_confirm .titlebar {
  text-align: center;
  font-weight: bold;
}

#html_confirm .buttons {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: baseline;

  gap: 1em;
}

JavaScript

// HTML dialog per https://www.lateral.co.za/writing/popups-and-promises
function html_confirm(message) {
	return new Promise( function(resolve, reject) {	
		let el = document.getElementById(`html_confirm`);
		el.querySelector(`.content`).innerHTML = message;

		// wire the no and yes buttons
		let hide = function() { el.classList.remove(`showing`); }
		el.querySelector(`.button-cancel`).addEventListener(`click`, function() {
			hide();
			reject();
		});
		el.querySelector(`.button-continue`).addEventListener(`click`, function() {
			hide();
			resolve();
		});
		// show the popup
		el.classList.add(`showing`);
	});
};

document.addEventListener(`DOMContentLoaded`, ()=>{
	document.getElementById('showPopup').addEventListener('click', function() {
  	html_confirm(`Do you want some coffee?`).then( 
    	()=>console.log(`You get coffee!`),
      ()=>console.warn(`You should probably have some coffee`)
      );
  });
});