Skip to content

Instantly share code, notes, and snippets.

@nfreear
Created February 13, 2022 16:13
Show Gist options
  • Select an option

  • Save nfreear/24975f6dcdd06adb1c308643e630cc53 to your computer and use it in GitHub Desktop.

Select an option

Save nfreear/24975f6dcdd06adb1c308643e630cc53 to your computer and use it in GitHub Desktop.
<dialog> - Modal Dialog Element Test
<!doctype html> <title> Dialog element test </title>
<meta charset=utf-8 />
<style>
body { margin: 1rem auto; max-width: 30rem; }
button, select { font-size: inherit; }
button { padding: .4rem 2rem; margin-right: 1rem; }
select { padding: .2rem 1rem; }
#my-dialog {
background: #fafafa;
border: 2px solid #bbb;
border-radius: .25rem;
box-shadow: 3px 3px 4px black;
X-min-width: 12rem;
}
/* Backdrop is only displayed when dialog is opened with dialog.showModal() */
#my-dialog::backdrop {
background: rgba(230, 230, 230, .8);
}
</style>
<h1> Dialog element test </h1>
<menu>
<button id="my-opener"> Open dialog </button>
</menu>
<dialog id="my-dialog">
<form method="dialog">
<h2> My dialog </h2>
<p><label> Favourite animal:
<select>
<option></option>
<option>Brine shrimp</option>
<option>Red panda</option>
<option>Spider monkey</option>
</select>
</label></p>
<menu>
<button value="cancel">Cancel</button>
<button id="confirmBtn" value="default">Confirm</button>
</menu>
</form>
</dialog>
<script>
const SHOW_BTN = document.querySelector('#my-opener');
const DIALOG = document.querySelector('#my-dialog');
const SELECT = DIALOG.querySelector('select');
const confirmBtn = DIALOG.querySelector('#confirmBtn');
console.assert(typeof DIALOG.showModal === 'function', '<dialog> not supported!');
SHOW_BTN.addEventListener('click', ev => {
console.debug('Opener button click.');
// DIALOG.open = true;
DIALOG.showModal();
});
DIALOG.addEventListener('close', ev => {
console.assert(DIALOG.returnValue === ev.target.returnValue);
console.debug('Dialog close. Return value:', ev.target.returnValue, ev);
});
SELECT.addEventListener('change', ev => {
console.debug('Select change:', ev.target.value, ev);
confirmBtn.value = ev.target.value;
});
</script>
<pre>
NDF, 11-Feb-2022.
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment