HTMLDialogElement: showModal() メソッド

Baseline 2022

Newly available

Since March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

showModal()HTMLDialogElement インターフェイスのメソッドで、ダイアログをモーダルに、見えるように他のダイアログの最も上に表示します。これは 最上位レイヤー の中に ::backdrop 擬似要素とともに表示されます。ダイアログの外の操作はブロックされ、ダイアログの外のコンテンツは不活性にレンダリングされます。

構文

js
showModal()

引数

なし。

返値

なし (undefined)。

Exceptions

InvalidStateError DOMException

ダイアログが既に開いている場合(すなわち、open 属性が既に <dialog> 要素に設定されている場合)、またはダイアログが既に示されているポップオーバーである場合も発生します。

モーダルダイアログを開く

次の例は、クリックするとフォームを含むモーダル <dialog>HTMLDialogElement.showModal() 関数で開くボタンを示しています。開いている間、モーダルダイアログのコンテンツ以外は不活性になります。ここから、Cancel ボタンをクリックしてダイアログを閉じたり(HTMLDialogElement.close() 関数で)、submit ボタンによってフォームを送信したりすることができます。キャンセルボタンを選択するとダイアログが閉じられ、close イベントが作成されますが、cancel イベントは作成されません。

HTML

html
<!-- pop-up dialog box, containing a form -->
<dialog id="favDialog">
  <form method="dialog">
    <p>
      <label for="favAnimal">Favorite animal:</label>
      <select id="favAnimal" name="favAnimal">
        <option></option>
        <option>Brine shrimp</option>
        <option>Red panda</option>
        <option>Spider monkey</option>
      </select>
    </p>
    <div>
      <button id="cancel" type="reset">Cancel</button>
      <button type="submit">Confirm</button>
    </div>
  </form>
</dialog>

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

JavaScript

js
const updateButton = document.getElementById("updateDetails");
const cancelButton = document.getElementById("cancel");
const dialog = document.getElementById("favDialog");
dialog.returnValue = "favAnimal";

function openCheck(dialog) {
  if (dialog.open) {
    console.log("Dialog open");
  } else {
    console.log("Dialog closed");
  }
}

// Update button opens a modal dialog
updateButton.addEventListener("click", () => {
  dialog.showModal();
  openCheck(dialog);
});

// Form cancel button closes the dialog box
cancelButton.addEventListener("click", () => {
  dialog.close("animalNotChosen");
  openCheck(dialog);
});

結果

仕様書

Specification
HTML Standard
# dom-dialog-showmodal-dev

ブラウザーの互換性

BCD tables only load in the browser

関連情報

  • このインターフェイスを実装している HTML 要素: <dialog>