0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】クリックしたときにポップアップを表示する

Posted at

イメージ図

ポップアップ.png

HTML

<button id="click-btn">クリック!</button>
<div id="popup-wrapper">
  <div id="popup-inside">
    <div id="close">x</div>
      <div id="message">
      <h2>あの人気のマンガが...</h2>
      <p>今なら80%オフ!</p>
      <a href="#">ゲットする</a>
    </div>
  </div>
</div>

CSS

#click-btn {
  display: block;
  margin: 20px auto;
  background-color: purple;
  color: white;
  border: 0;
  padding: 6px 10px;
}

#popup-wrapper {
  background-color: rgba(0, 0, 0, .5);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: none;
}

#popup-inside {
  text-align: center;
  width: 100%;
  max-width: 300px;
  background: white;
  margin: 10% auto;
  padding: 20px;
  position: relative;
}

#message a {
  background: purple;
  color: white;
  text-decoration: none;
  padding: 6px 10px;
}

#close {
  position: absolute;
  top: 0;
  right: 5px;
  cursor: pointer;
}

JavaScript

const clickBtn = document.getElementById('click-btn');
const popupWrapper = document.getElementById('popup-wrapper');
const close = document.getElementById('close');

// ボタンをクリックしたときにポップアップを表示させる
clickBtn.addEventListener('click', () => {
  popupWrapper.style.display = "block";
});

// ポップアップの外側又は「x」のマークをクリックしたときポップアップを閉じる
popupWrapper.addEventListener('click', e => {
  if (e.target.id === popupWrapper.id || e.target.id === close.id) {
    popupWrapper.style.display = 'none';
  }
});
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?