<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="./style.css">
  <title>modal practice</title>
</head>
<body>
  <div class="container">
    <a href="" class="modal_open link">モーダルを開きます</a>
  </div>
  <div class="modal">
    <p class="modal_title">modal title</p>
    <p class="modal_text">
      モーダルのテキストが表示されます。
    </p>
  </div>
  <div class="modal_overlay"></div>

  <script src="./index.js"></script>
</body>
</html>
html, body {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

.container {
  padding: 40px;
  height: 100%;
  width: 100%;
  /* add style */
  position: relative;
}

.link {
  color: #ff8025;
  font-size: 12px;
}
.link:hover {
  color: #ffa769;
}

/* modal style */
.modal {
  display: none;
  border: 1px solid #dddddd;
  padding: 20px;
  width: 400px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
}
.modal_overlay {
  background: transparent;
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  z-index: 9;
}
.modal_title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333333;
}
.modal_text {
  font-size: 12px;
  color: #404040;
}
.modal.show, .modal_overlay.show {
  display: block;
}
// modal_open クラスがついた要素を取得
var link = document.getElementsByClassName('modal_open')[0];
// modal classがついた要素を取得
var modal = document.getElementsByClassName('modal')[0];
// modal_overlay classがついた要素を取得
var overlay = document.getElementsByClassName('modal_overlay')[0];

// link押下時にクリックイベントを発火させる
link.addEventListener('click', function(e){
  if (!modal.classList.contains('show')){
    // modalクラスが付いている要素に表示させるクラスを追加
    modal.classList.add('show');
    overlay.classList.add('show');
  }

  e.preventDefault();
});

overlay.addEventListener('click', function() {
  if (modal.classList.contains('show')) {
    console.log(this);
    modal.classList.remove('show');
    this.classList.remove('show');
  }
})
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.