JSFiddle - React, Tailwind, and code Playground

by dandclark_msft

HTML

<h1>Example: focus on dialog close; focusable children of dialog</h1>

<p tabindex="0">I am focusable</p>

<dialog id="favDialog">
  <form method="dialog">
    <p><label>Favorite animal:
      <select>
        <option></option>
        <option>Brine shrimp</option>
        <option>Red panda</option>
        <option>Spider monkey</option>
      </select>
    </label></p>
    <menu>
      <button id="cancel" value="cancel">Cancel</button>
      <button id="confirmBtn" value="default">Confirm</button>
    </menu>
  </form>
</dialog>

<button id="updateDetails">Update details</button>

<p tabindex="0">I am focusable</p>

<output aria-live="polite"></output>

<h2>Findings</h2>

<ul>
  <li>Focus remains on whichever child element of dialog had focus at time of closure, including if dismissed by ESC key</li>
  <li>Pressing tab will move focus to the next focusable element in the root document (as opposed to next focusable element in hidden dialog)</li>
</ul>

CSS

:focus {
  border: 3px solid red;
}

output {
  font-weight: 700;
}

JavaScript

var updateButton = document.getElementById('updateDetails');
var favDialog = document.getElementById('favDialog');
var outputBox = document.querySelector('output');
var selectEl = document.querySelector('select');
var confirmBtn = document.getElementById('confirmBtn');

// "Update details" button opens the <dialog> modally
updateButton.addEventListener('click', function onOpen() {
  if (typeof favDialog.showModal === "function") {
    favDialog.showModal();
    outputBox.value = "";
  } else {
    alert("The <dialog> API is not supported by this browser");
  }
});

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

/*// "Confirm" button of form triggers "close" on dialog because of [method="dialog"]
favDialog.addEventListener('close', function onClose() {
	updateOutput();
});

// Add event listener to ESC key
document.onkeydown = function(e) {
	if (e.keyCode === 27) {
  	updateOutput();
  }
};*/

setInterval(() => { outputBox.value = "Active element is " + document.activeElement}, 200);

function updateOutput() {
	outputBox.value = "Active element is " + document.activeElement;
  
  if (document.activeElement.id) {
  	outputBox.value = outputBox.value + " with #" + document.activeElement.id;
  }
}

favDialog.addEventListener("close", () => console.log("close event"));
favDialog.addEventListener("cancel", () => console.log("cancel event"));