■HTMLを用意
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery</title>
<link rel="stylesheet" href="css/style.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<!-- 初期時点で表示されているエリア -->
<div id="front-layer">
<h1>Alert box</h1>
<button id="here-btn">Click here!</button>
</div>
<!-- 初期時点では非表示のエリア -->
<div id="back-layer">
<div id="alert-box">
<p>Confirm!</p>
<button id="ok-btn">OK</button>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script src="js/script.js"></script>
</body>
</html>
■CSSを用意
style.css
/* 初期時点で表示されているエリアのスタイル */
# front-layer {
padding-top: 40px;
text-align: center;
}
/* Click here!ボタンのスタイル */
# here-btn {
width: 100px;
padding-top: 8px;
padding-bottom: 8px;
font-size: 16px;
background-color: blue;
color: white;
border: none;
cursor: pointer;
box-shadow: 0 3px rgba(0, 0, 0, .4);
outline: none;
}
/* Click here!ボタン押下時のスタイル */
# here-btn:active {
box-shadow: none;
position: relative;
top: 3px;
}
/* 初期時点で非表示のエリアのスタイル */
# back-layer {
position: fixed;
left: 0;
top: 0;
height: 100%;
width: 100%;
background: rgba(0, 0, 0, .4);
}
/* アラートボックスのスタイル */
# alert-box {
margin: 50px auto 0;
text-align: center;
background-color: white;
padding-top: 14px;
padding-bottom: 30px;
width: 50%;
}
/* アラートボックスのテキストスタイル */
p {
font-size: 22px;
}
/* アラートボックスのボタンスタイル */
# ok-btn {
width: 60px;
padding-top: 6px;
padding-bottom: 6px;
font-size: 16px;
background-color: green;
color: white;
border: none;
cursor: pointer;
box-shadow: 0 3px rgba(0, 0, 0, .4);
outline: none;
}
/* アラートボックスのボタン押下時のスタイル */
# ok-btn:active {
box-shadow: none;
position: relative;
top: 3px;
}
■jQueryを用意
script.js
$(document).ready(() => {
// 初期状態で非表示にしたいエリアを非表示に設定
$("#back-layer").hide();
// Click here!ボタンクリックイベントを設定
$("#here-btn").click(() => {
$("#back-layer").fadeIn(100);
});
// okボタンクリックイベントを設定
$("#ok-btn").click(() => {
$("#back-layer").fadeOut(100);
});
// Enterキーアップイベントを設定
$(document).keyup((e) => {
if (e.key === "Enter") {
$("#back-layer").fadeOut(100);
}
});
});
■メインポイント
ポイントは以下です。
①初期時点で非表示としたい要素はhide()を使用
②イベント発火時点で表示/非表示を切り替えるときはfadeIn()、fadeOut()
■+αポイント
その他実装時に気をつけた箇所は以下です。
①ボタン押下時のボタンスタイルを制御
style.css
# ok-btn:active {
box-shadow: none;
position: relative;
top: 3px;
}
②アラートボックスに対して、Enterキー押下時(正しくはkeyup時)にも、okボタンクリックと同じ動きを実装
script.js
$(document).keyup((e) => {
if (e.key === "Enter") {
$("#back-layer").fadeOut(100);
}
});
■プレビュー
See the Pen ExNwYVj by dev-nakasho (@dev-nakasho) on CodePen.
以上です。