HTML

dialog要素の改善解説と使い方【HTML】

HTML5の進化に伴い、ウェブ開発者にとって便利な <dialog> 要素が大きく改善されました。この要素は、モーダルダイアログや通知の作成に非常に役立ちます。2023年には、これまで以上に柔軟な使用が可能となり、モーダル以外のダイアログも簡単に作成できるようになりました。

この記事では、具体的な改善点の解説に加えて、実際のコード使用例を交えながら紹介します。

新機能1: モーダル以外のダイアログの作成

従来、<dialog> 要素はモーダルダイアログのためのものでしたが、今では非モーダルダイアログもサポートしています。これにより、ユーザーがダイアログを開いている間でも、他の操作を継続できる柔軟なUIを作成可能です。

 

新機能2: show(), showModal(), close() メソッド

これらのメソッドにより、JavaScriptを使って簡単にダイアログを制御できます。

  • show() メソッド
    非モーダルなダイアログを表示します。
  • showModal() メソッド
    ページ全体を覆うモーダルダイアログを表示します。これが表示されている間は、他のページ操作が制限されます。
  • close() メソッド
    ダイアログを閉じるためのメソッドで、ユーザーのアクションに応じたダイアログの閉鎖が可能です。

実際のコード例

では、上記の機能を使ったサンプルコードを見ていきましょう。

1. 非モーダルダイアログの表示

See the Pen
dialog01
by Rin (@rinblog0408)
on CodePen.

 

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Non-modal Dialog Example</title>
</head>
<body>

  <button id="open-dialog">Open Non-modal Dialog</button>
  <dialog id="non-modal-dialog">
    <p>This is a non-modal dialog. You can still interact with other parts of the page.</p>
    <button id="close-dialog">Close</button>
  </dialog>

  <script>
    const dialog = document.getElementById('non-modal-dialog');
    const openButton = document.getElementById('open-dialog');
    const closeButton = document.getElementById('close-dialog');

    openButton.addEventListener('click', () => {
      dialog.show(); // 非モーダルダイアログを表示
    });

    closeButton.addEventListener('click', () => {
      dialog.close(); // ダイアログを閉じる
    });
  </script>

</body>
</html>

 

2. モーダルダイアログの表示

See the Pen
dialog02
by Rin (@rinblog0408)
on CodePen.

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Modal Dialog Example</title>
</head>
<body>

  <button id="open-modal-dialog">Open Modal Dialog</button>
  <dialog id="modal-dialog">
    <p>This is a modal dialog. You cannot interact with the page until it's closed.</p>
    <button id="close-modal-dialog">Close</button>
  </dialog>

  <script>
    const modalDialog = document.getElementById('modal-dialog');
    const openModalButton = document.getElementById('open-modal-dialog');
    const closeModalButton = document.getElementById('close-modal-dialog');

    openModalButton.addEventListener('click', () => {
      modalDialog.showModal(); // モーダルダイアログを表示
    });

    closeModalButton.addEventListener('click', () => {
      modalDialog.close(); // ダイアログを閉じる
    });
  </script>

</body>
</html>

 

2023年の <dialog> 要素の改善により、ウェブアプリケーション開発者はより簡単にモーダルや非モーダルダイアログを作成できるようになりました。show(), showModal(), close() メソッドを使えば、ダイアログの操作がさらに柔軟になります。

ABOUT ME
りん
沖縄から福岡に移住。QA/Webデザイナー/SE/フリーランス/SE人事など。趣味や好きなことをブログにまとめてます。