ウィンドウオブジェクトのメソッドopenを使って、モーダルを作成したいと思います。
以下、用語の説明がありますが、知っている方は読み飛ばして問題ありません。
モーダルとは
画面の上に別のウィンドウを表示し、ユーザーに情報を伝える画面のことを指します。
表示された別ウィンドウで特定の操作を行わないとほかの操作ができません。
したがって、モーダルは、画面上の操作をコントールすることを目的として利用されます。
Window.openとは
ブラウザで表示されるウィンドウオブジェクト(window)のopenメソッドであり、ウィンドウを生成します。
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
ソースコード
親画面
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>ParentWindow</title>
</head>
<style>
#layer{
background: rgba(0, 0, 0, 0.5);
position: fixed;
top: 0px;
right: 0px;
left: 0px;
bottom: 0px;
z-index: -1;
visibility: hidden;
}
#layer.is-open{
z-index: 100;
visibility: visible;
}
</style>
<body>
<div id="layer"></div>
<p>あなたが入力した値は、"<span id="outputText"></span>"です。</p>
<button onclick="overlay()">子ウィンドウ</button>
<script>
function overlay(){
const layer = document.getElementById("layer");
// オーバーレイを表示
layer.classList.add("is-open");
// 子画面を生成
const wWidth = 300;
const wHeight = 500;
const wTop = window.screenTop + (window.innerHeight / 2) - (wHeight / 2);
const wLeft = window.screenLeft + (window.innerWidth / 2) - (wWidth / 2);
window.open("subWindow.html",self,"height=" + wHeight + ",width=" + wWidth + ",top=" + wTop + ",left=" + wLeft);
}
function addText(inputText) {
// 子画面からの値を取得&表示
document.getElementById("outputText").textContent = inputText;
}
function closeWindow() {
// オーバーレイを閉じる
const layer = document.getElementById("layer");
layer.classList.remove("is-open");
}
</script>
</body>
</html>
子画面
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>childWindow</title>
</head>
<body>
<input id="text">
<button onclick="closeWindow()">閉じる</button>
<script>
function closeWindow() {;
// オーバーレイを閉じる
window.opener.closeWindow();
// 値を親画面へ渡す
const inputText = document.getElementById("text").value;
window.opener.addText(inputText);
// 自画面を閉じる
window.close();
}
window.addEventListener("beforeunload",() => {
// オーバーレイを閉じる
window.opener.closeWindow();
window.close();
});
</script>
</body>
</html>
ソースコードのポイント
親ウィンドウで「子ウィンドウ」をクリックすることでオーバーレイ(上に覆っているもの)を表示させることによって、親ウィンドウを操作させなくします。また、同時に子ウィンドウを表示させます。
childWindow.htmlにあるwindow.opener
は、親ウィンドウオブジェクト(parentWindow.html)を指し、親ウィンドウのメソッドを指定しています。
子ウィンドウで閉じるボタンを押すとオーバーレイを非表示にさせ、親ウィンドウの操作を可能にしています。
このとき子ウィンドウで値を代入していた場合、addTextメソッドで親ウィンドウに表示されます。
また、window.close()
で子ウィンドウを閉じています。
window.addEventListener("beforeunload",() => {
は、子ウィンドウで×ボタンを押したときの処理になります。
動作確認
親ウィンドウを開きます。
![](https://enjoy-pglife.com/wp-content/uploads/Articles/2023/1-3.png)
子ウィンドウをクリックし、子ウィンドウを表示させます。
![](https://enjoy-pglife.com/wp-content/uploads/Articles/2023/2-2.png)
適当に値を入力してみましょう。
![](https://enjoy-pglife.com/wp-content/uploads/Articles/2023/3-1.png)
「閉じる」ボタンをクリックします。
![](https://enjoy-pglife.com/wp-content/uploads/Articles/2023/4-1.png)
親ウィンドウに値が出力されていることがわかるかと思います。
また、子ウィンドウが表示されている間は、親ウィンドウが操作できないことも確認できるかと思います。
以上、window.openでモーダルを作成してみました。