モーダルウィンドウ - Javascript

モーダルウィンドウとは?

モーダルウィンドウは、元のウィンドウの上に別で表示されるウィンドウのことです。

コード

index.html

 <p>「 ? 」をクリックしてください。<img id="question" class="question" src="/images/question.svg" alt=""></p>
<div id="modal_wrapper">
  <div id="explain">
    <h1>モーダルウィンドウ</h1>
  </div><!-- /div#explain -->
</div><!-- /div#modal_wrapper -->

script.js

window.addEventListener('load', function(){
  const question = document.getElementById('question');
  const modal_wrapper = document.getElementById('modal_wrapper');
  const explain = document.getElementById('explain');
  const html_ele = document.getElementsByTagName('html');
  const body_ele = document.getElementsByTagName('body');

  question.addEventListener('click', function() {
    modal_wrapper.classList.add('show');
    html_ele[0].classList.add('over');
    body_ele[0].classList.add('over');
  });

  modal_wrapper.addEventListener('click', function(event) {
    event.stopPropagation();
    if(modal_wrapper.classList.contains('show')){
      modal_wrapper.classList.remove('show');
      html_ele[0].classList.remove('over');
      body_ele[0].classList.remove('over');
    }
  });

  explain.addEventListener('click', function(event){
    event.stopPropagation();
  });
});

style.css

.question {
  width: 20px;
  cursor: pointer;
}
html.over, body.over {
  overflow: hidden;
}
#modal_wrapper {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0,0,0,0.5);
  pointer-events: none;
  opacity: 0;
  transition: 0.25s ease-out;
}
#modal_wrapper.show {
  opacity: 1;
  pointer-events: all;
}
#explain {
  position: absolute;
  width: 80%;
  height: 80%;
  padding: 10px 20px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  object-fit: cover;
  transition: 0.5s ease-out;
  background: white;
  overflow-y: scroll;
}

説明

以下のコードは、モーダルウィンドウの「 div要素の id="explain" 」がクリックされても、モーダルウィンドウが閉じないようにしています。

グレーの透過している部分をクリックするとモーダルウィンドウが閉じます。

explain.addEventListener('click', function(event){
  event.stopPropagation();
});

モーダルウィンドウ上でスクロールしても元ウィンドウがスクロールし内容にするには、html要素とbody要素に「 overflow: hidden 」を指定してスクロールしないようにします。

javascript で、html要素とbody要素に、クラス名「 over 」を追加し、モーダルウィンドウがクリックされると、クラス名「 over 」を削除します。