🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

モーダルウィンドウ(ポップアップ)

クリックでポップアップを表示する基本的なテンプレート

👀 実行デモ

👇 下のボタンをクリック 👇

💡 このテンプレートの使い道とメリット

  • ユーザーへのお知らせ・注意喚起・確認ダイアログに便利
  • 画像の拡大表示やフォーム表示にも応用可能
  • ページ遷移なしで情報を完結でき,UXが向上
  • スタイル調整でモダンなデザインに変更しやすい
  • 背景を暗くすることで注目させたい内容を強調できる

📋 コピーして貼り付けできるコード


<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>モーダルウィンドウ</title>
  <style>
    /* モーダルオーバーレイの背景 */
    .modal-overlay {
      display: none; /* 初期状態は非表示 */
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5); /* 半透明の背景 */
      z-index: 1000; /* モーダルが他の要素より前に表示される */
    }

    /* モーダルウィンドウ */
    .modal {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%); /* 中央に配置 */
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      width: 300px;
      text-align: center;
    }

    /* 閉じるボタン */
    .close-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      background: none;
      border: none;
      font-size: 20px;
      cursor: pointer;
    }

    /* ボタンのスタイル */
    button {
      padding: 10px 20px;
      font-size: 1rem;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <section>
    <h2>👀 実行デモ</h2>
    <div style="text-align: center; font-size: 1.7rem; margin: 1rem 0;">👇 下のボタンをクリック 👇</div>
    <button onclick="openModal()">モーダルを開く</button>

    <!-- モーダルのオーバーレイ -->
    <div class="modal-overlay" id="modal">
      <div class="modal">
        <button class="close-btn" onclick="closeModal()">×</button>
        <h3>お知らせ</h3>
        <p>これはモーダルウィンドウです。外側をクリックするか × ボタンで閉じられます。</p>
      </div>
    </div>
  </section>

  <script>
    // モーダルを開く関数
    function openModal() {
      document.getElementById('modal').style.display = 'block'; // モーダルを表示
    }

    // モーダルを閉じる関数
    function closeModal() {
      document.getElementById('modal').style.display = 'none'; // モーダルを非表示
    }

    // モーダルの外側クリックでも閉じる
    document.querySelector('.modal-overlay').addEventListener('click', function(event) {
      if (event.target === document.querySelector('.modal-overlay')) {
        closeModal();
      }
    });
  </script>

</body>
</html>
    

🧩 応用と活用方法

モーダルウィンドウは、ユーザーに特定の情報を注目してもらいたいときに非常に効果的です。onclick イベントを用いて表示・非表示を制御する仕組みはシンプルながら、実際のUIでは頻繁に活用されます。

たとえば、画像の拡大表示や、会員登録・問い合わせフォームを別ページに遷移させずに提示したい場合などに最適です。また、document.getElementById("modal").style.display = "flex" のような記述によって、背景を暗くしつつ中央にポップアップを表示する設計が可能になります。

閉じる処理には closeModal() 関数で style.display"none" に変更するだけで完了し、コード量が少ない点も魅力です。

なお、UI/UX をさらに向上させたい場合は、背景クリックでの自動クローズ処理や、Esc キーによる閉じるイベントを追加するのも良いアプローチです。JavaScriptの初学者にとっては、DOM操作とイベント処理の入門としても最適なテーマといえるでしょう。