《jQeury》サイトにアクセスした時にモーダルを自動で表示する
公開日:2025年07月29日 最終更新日:2025年7月29日
サイトにアクセスした際に、モーダルウィンドウを自動で開いた状態にする方法です。
モーダルの背景(黒の半透明オーバーレイ)をクリックすると非表示になります。
ページをリロードすると、再びモーダルが表示されます。
DEMO
わかりやすいように、別ページにDEMOを用意しました。
HTML
<div class="modal">
<div class="modal-overlay">
<div class="modal-content">
<p>モーダルウィンドウ</p>
<p><a href="https://blog.grinee.net/">リンク</a></p>
<img src="https://blog.grinee.net/demo/images/image1.png">
</div>
<span class="modal-close">×</span>
</div>
</div>
CSS
.modal {
background-color: rgba(68, 68, 68, .8);
display: none; /* 初期非表示 */
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: 10;
}
.modal-overlay {
align-items: center;
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
}
.modal-content {
background: #fff;
max-height: calc(90% - 40px);
max-width: calc(90% - 40px);
overflow-y: auto;
padding: 20px;
text-align: center;
}
.modal-close {
background: none;
border: none;
color: #fff;
cursor: pointer;
font-size: 40px;
}
.modal img {
max-width: 100%;
}
JavaScript
記述の前にjQueryの読み込みが必要です。
jQuery(function ($) {
$(".modal").show();
$(".modal-content").on("click", function (e) {
e.stopPropagation();
});
$(".modal").on("click", function () {
$(".modal").fadeOut();
return false;
});
});