JavaScriptでモーダルウィンドウを実装する方法|HTML・CSSとの組み合わせ解説

クリックするとポップアップのように表示されるモーダルウィンドウ。通知やフォーム、画像拡大など、さまざまな用途に使われるUIです。この記事ではHTML・CSS・JavaScriptを使った基本的な実装方法を紹介します。

完成イメージ

  • ボタンを押すと中央にモーダルが表示
  • 背景が暗くなり、モーダル以外を操作不可に
  • 閉じるボタンや背景クリックで非表示

HTML構造

<button id="openModal">モーダルを開く</button>

<div id="modal" class="modal">
  <div class="modal-content">
    <span class="close-button">×</span>
    <p>ここがモーダルの内容です。</p>
  </div>
</div>

CSSでスタイルを整える

.modal {
  display: none;
  position: fixed;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  justify-content: center;
  align-items: center;
}

.modal-content {
  background: white;
  padding: 20px;
  max-width: 400px;
  border-radius: 8px;
  position: relative;
}

.close-button {
  position: absolute;
  right: 10px;
  top: 10px;
  cursor: pointer;
  font-size: 24px;
}

JavaScriptで開閉処理を制御

document.addEventListener("DOMContentLoaded", () => {
  const modal = document.getElementById("modal");
  const openBtn = document.getElementById("openModal");
  const closeBtn = document.querySelector(".close-button");

  openBtn.addEventListener("click", () => {
    modal.style.display = "flex";
  });

  closeBtn.addEventListener("click", () => {
    modal.style.display = "none";
  });

  window.addEventListener("click", (e) => {
    if (e.target === modal) {
      modal.style.display = "none";
    }
  });
});

おわりに

モーダルウィンドウは、ユーザーの注意を引きたいときや、重要な情報を表示する場面にとても便利なUIです。今回の方法をベースに、フォームや画像ギャラリーなどにも応用できます。

次回は「スクロール禁止処理」や「フェードアニメーション付きのモーダル」もご紹介予定です!