<h1>JavaScriptでポップアップウィンドウを実装する方法</h1>

<h2>サンプル1: window.open()メソッドを使用したポップアップ</h2>
<button id="open-popup">ポップアップを開く</button>

<h2>サンプル2: CSSとJavaScriptを使ったモーダルウィンドウ</h2>
<button id="open-modal">モーダルを表示</button>

<div id="modal" class="popup">
  <div class="popup-content">
    <h2>ポップアップタイトル</h2>
    <p>これはCSSとJavaScriptを使ったモーダルポップアップです。</p>
    <button id="close-modal">閉じる</button>
  </div>
</div>
/* ボタンとポップアップの基本スタイル */
button {
  margin: 10px;
  padding: 10px;
  font-size: 16px;
}

.popup {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  background-color: #fff;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
  max-width: 400px;
  text-align: center;
}
// サンプル1: window.open()を使ったポップアップウィンドウの実装
document.getElementById('open-popup').addEventListener('click', function() {
  window.open('https://example.com', 'popupWindow', 'width=400,height=300');
});

// サンプル2: CSSとJavaScriptを使ったモーダルウィンドウの実装
document.getElementById('open-modal').addEventListener('click', function() {
  document.getElementById('modal').style.display = 'block';
});

document.getElementById('close-modal').addEventListener('click', function() {
  document.getElementById('modal').style.display = 'none';
});

// モーダル外をクリックした時にモーダルを閉じる
window.addEventListener('click', function(event) {
  if (event.target === document.getElementById('modal')) {
    document.getElementById('modal').style.display = 'none';
  }
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.