画面中央にポップアップするモーダルウィンドウ

ボタンクリックで画面中央にポップアップするモーダルウィンドウ(ダイアログ)を作るためのコードです。
目次
仕様
- ボタンをクリックするとモーダルウィンドウが表示される
- モーダルウィンドウが表示されている時は背景を暗くし、スクロールも無効化する
- 背景をクリックしたらモーダルウィンドウを閉じる
HTML
<div class="modal_btn">ここをクリック</div> <div class="modal_wrap"> <div class="modal_content"> ~~~ </div> </div>
ボタンには.modal_btn、モーダルウィンドウを中央寄せするためのラッパーには.modal_wrap、本体には.modal_contentというクラスを付与します。
JavaScript
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('.modal_btn').addEventListener('click', function() {
document.body.style.overflow = 'hidden';
document.querySelector('.modal_wrap').classList.add('show');
});
document.querySelector('.modal_wrap').addEventListener('click', function() {
document.body.style.overflow = 'auto';
this.classList.remove('show');
});
document.querySelector('.modal_content').addEventListener('click', function(e) {
e.stopPropagation();
});
});
ボタンクリックで.modal_wrapに.showというクラスを付与し、モーダルウィンドウの表示を制御しています。
その他に、背景クリックで閉じる(.showを削除する)機能と、モーダルウィンドウ内でのクリックイベントの制御、背景のロック(bodyのoverflowで制御する)機能を実装しています。
jQuery版
jQueryを使用する場合はこちらです。
$(document).ready(function() {
$('.modal_btn').on('click', function() {
$('body').css('overflow', 'hidden');
$('.modal_wrap').addClass('show');
});
$('.modal_wrap').on('click', function() {
$('body').css('overflow', 'auto');
$(this).removeClass('show');
});
$('.modal_content').on('click', function(e) {
e.stopPropagation();
});
});
CSS
※装飾のためのコードは一部省略し、必須部分のみ記載
.modal_btn{
/* ボタンの装飾(省略) */
}
.modal_wrap{
display: flex;
justify-content: center;
align-items: center;
opacity: 0;
visibility: hidden;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
transition: 0.5s;
}
.modal_wrap.show {
opacity: 1;
visibility: visible;
}
.modal_content{
/* モーダルウィンドウの装飾(省略) */
overflow-y: auto;
max-height: 80vh;
background: #fff;
}
実際の動作
See the Pen Untitled by Leo_8192 (@Leo_8192) on CodePen.