Last active
September 7, 2022 17:07
-
-
Save luismartinezs/04901979e4e31f8a21d65b0a4c40f398 to your computer and use it in GitHub Desktop.
Dialogs #a11y #html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog --> | |
<dialog open> | |
<p>Greetings, one and all!</p> | |
<!-- method="dialog" closes dialog on form submit --> | |
<form method="dialog"> | |
<button>OK</button> | |
</form> | |
</dialog> | |
<!-- Simple modal dialog containing a form --> | |
<dialog id="favDialog"> | |
<form method="dialog"> | |
<p> | |
<label | |
>Favorite animal: | |
<select> | |
<option value="default">Choose…</option> | |
<option>Brine shrimp</option> | |
<option>Red panda</option> | |
<option>Spider monkey</option> | |
</select> | |
</label> | |
</p> | |
<div> | |
<button value="cancel">Cancel</button> | |
<button id="confirmBtn" value="default">Confirm</button> | |
</div> | |
</form> | |
</dialog> | |
<p> | |
<button id="updateDetails">Update details</button> | |
</p> | |
<output></output> | |
<script> | |
const updateButton = document.getElementById("updateDetails"); | |
const favDialog = document.getElementById("favDialog"); | |
const outputBox = document.querySelector("output"); | |
const selectEl = favDialog.querySelector("select"); | |
const confirmBtn = favDialog.querySelector("#confirmBtn"); | |
// If a browser doesn't support the dialog, then hide the | |
// dialog contents by default. | |
if (typeof favDialog.showModal !== "function") { | |
favDialog.hidden = true; | |
/* a fallback script to allow this dialog/form to function | |
for legacy browsers that do not support <dialog> | |
could be provided here. | |
*/ | |
} | |
// "Update details" button opens the <dialog> modally | |
updateButton.addEventListener("click", () => { | |
if (typeof favDialog.showModal === "function") { | |
favDialog.showModal(); | |
} else { | |
outputBox.value = | |
"Sorry, the <dialog> API is not supported by this browser."; | |
} | |
}); | |
// "Favorite animal" input sets the value of the submit button | |
selectEl.addEventListener("change", (e) => { | |
confirmBtn.value = selectEl.value; | |
}); | |
// "Confirm" button of form triggers "close" on dialog because of [method="dialog"] | |
favDialog.addEventListener("close", () => { | |
outputBox.value = `${ | |
favDialog.returnValue | |
} button clicked - ${new Date().toString()}`; | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment