【2022年11月】モーダルウィンドウ背景固定・スクロール位置保持・開閉トグル(pureJS)

2022年11月29日

HTML

<a class="togglebtn" role="button" id="togglebtn" data-close-btn></a>

<div id="modal" class="modal">
  <div id="modal-bg" class="modal-bg" data-close-btn></div>
  <div class="modal-panel" id="modal-panel">
    <div class="modal-head"><button data-close-btn><span class="material-symbols-outlined">close</span></button></div>
    <div class="modal-content">
     ここにコンテンツをいれる
    </div>
  </div>
</div>

CSS

body.fixed {
  /*モーダル背景固定*/
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  user-select: none;
}

.modal {
  display: none;
  z-index: 3;
}


.modal.show {
  display: block;
}

.modal-bg {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 2;
  background: rgba(0, 0, 0, 0.6);
  justify-content: center;
  align-items: center;
}

.modal-panel {
  background-color: #fafafa;
  width: 100%;
  overflow: auto;
  box-sizing: border-box;
  position: absolute;
  bottom: 80px;
  pointer-events: auto;
  z-index: 10;
}

.modal-close {
  text-align: center;
  width: 42px;
  height: 42px;
  color: #444;
  background-color: #eee;
  cursor: pointer;
}
var scrollPosition;

document.addEventListener('DOMContentLoaded',
  function () {

    const elements = document.querySelectorAll('[data-close-btn]');

    elements.forEach(function (element) {
      element.addEventListener('click', function (event) {
        // 
        console.log(arguments[0]);
        const modal = document.getElementById('modal')
        modal.classList.toggle('show')
        if (modal.classList.contains('show')) {
          scrollPosition = document.scrollingElement.scrollTop
          document.body.classList.add('fixed')
          document.body.setAttribute('style', 'top:-' + scrollPosition + 'px')
        }
        else {
          document.body.classList.remove('fixed')
          window.scrollTo(0, scrollPosition);
        }

      }, false);


      const modalPanel = document.getElementById('modal-panel')
      modalPanel.addEventListener('click', function (event) {
        console.log(modalPanel);
        event.stopPropagation();
      });

    });



  }
);