An accessible modal with focus handling

Move focus into the dialog, keep Tab inside it and return focus to the button afterwards.

jQuery · An accessible modal with focus handlingAdvanced
let $opener = null;

function openDialog($dlg, $from) {
  $opener = $from;
  $dlg.attr({ role: 'dialog', 'aria-modal': 'true' }).show().find('button, a, input').filter(':first').focus();

  $dlg.on('keydown.dlg', function (e) {
    if (e.key === 'Escape') return closeDialog($dlg);
    if (e.key !== 'Tab') return;
    const $f = $dlg.find('button, a[href], input, select, textarea');
    const first = $f.first()[0], last = $f.last()[0];
    if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
    else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
  });
}

function closeDialog($dlg) {
  $dlg.off('keydown.dlg').hide();
  if ($opener) $opener.focus();
}
modalfocus trapariaaccessibility