<dialog id="favDialog">
  <h3>My new dialog</h3>
  <form method="dialog">
    <p>When using HTMLDialogElement.showModal() to open a `dialog`, focus is set on the first nested focusable element.</p>
    <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" formmethod="dialog">Cancel</button>
      <button id="confirmBtn" value="default">Confirm</button>
    </div>

    <div>
      <button type="reset" onclick="favDialog.close()">Cancel</button>
      <button type="submit">Save</button>
    </div>
  </form>
</dialog>

<button onclick="favDialog.showModal()">Open Dialog</button>

<output></output>

<div style="margin-top:4rem;">
  <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#examples" target="_blank">Read More</a>
</div>
dialog::backdrop {
  /*   background-color: rgba(0, 0, 255, 0.2); */
}

/* animation */
dialog {
  opacity: 0;
  scale: 0;
  display: block;
  transition: all 1s;
}

dialog[open] {
  opacity: 1;
  scale: 1;
}
const favDialog = document.getElementById("favDialog");
const outputBox = document.querySelector("output");
const selectEl = favDialog.querySelector("select");
const confirmBtn = favDialog.querySelector("#confirmBtn");

// "Favorite animal" input sets the value of the submit button
selectEl.addEventListener("change", (e) => {
  confirmBtn.value = selectEl.value;
});

// "Cancel" button closes the dialog without submitting because of [formmethod="dialog"], triggering a close event.
favDialog.addEventListener("close", (e) => {
  outputBox.value =
    favDialog.returnValue === "default"
      ? "No return value."
      : `ReturnValue: ${favDialog.returnValue}.`; // Have to check for "default" rather than empty string
});

// Prevent the "confirm" button from the default behavior of submitting the form, and close the dialog with the `close()` method, which triggers the "close" event.
confirmBtn.addEventListener("click", (event) => {
  event.preventDefault(); // We don't want to submit this fake form
  favDialog.close(selectEl.value); // Have to send the select box value here.
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.