HTMLDialogElement

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.

HTMLDialogElement インターフェイスは <dialog> 要素を操作するメソッドを提供します。 HTMLElement インターフェースからプロパティとメソッドを継承しています。

EventTarget Node Element HTMLElement HTMLDialogElement

インスタンスプロパティ

親である HTMLElement から継承したプロパティがあります。

HTMLDialogElement.open

論理値で、ダイアログが操作可能であることを示す open 属性の値を反映します。

HTMLDialogElement.returnValue

文字列で、ダイアログの返値を設定または返却します。

インスタンスメソッド

親である HTMLElement から継承したメソッドがあります。

HTMLDialogElement.close()

ダイアログを閉じます。任意で引数として文字列を渡すことができ、これがダイアログの returnValue を更新します。

HTMLDialogElement.show()

ダイアログをモードレスで開きます。すなわち、その間にダイアログの外のコンテンツが操作できます。

HTMLDialogElement.showModal()

ダイアログをモーダルで、他のダイアログがあればその最も上に表示します。ダイアログの外の操作はブロックされます。ダイアログの外はすべて inert となり、ダイアログの外の操作はブロックされます。

イベント

cancel

ユーザーがエスケープキーで現在開いているダイアログを解除したときに発行されます。

close

エスケープキー、HTMLDialogElement.close() メソッド、または method="dialog" でダイアログ内のフォームを送信することによって、このダイアログが閉じられたときに発行されます。

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

以下の例はボタンを表示し、クリックすると、フォームの入ったモーダルダイアログ (<dialog>) を HTMLDialogElement.showModal() 関数によって開きます。そこから Cancel ボタンを押して (HTMLDialogElement.close() 関数で) ダイアログを閉じるか、送信ボタンでフォームを送信するかします。Cancel ボタンを選択すると、close イベントを生成します。cancel イベントではありません。

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
# htmldialogelement

ブラウザーの互換性

BCD tables only load in the browser

関連情報

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