<html>
<head>
<title>JavaScript</title>
<style>
.modalWrapper {
display: none;
}
.modalWrapper.showModal {
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
overflow-y: scroll;
}
.modalBody .h2 {
background-color: black;
color: white;
font-size: 2em;
}
.modalBody footer {
text-align: center;
font-size: 0.8em;
background-color: #222;
color: white;
padding: 5px;
}
.modalBody {
width: 50%;
left: 25%;
top: 10%;
position: absolute;
background-color: aliceblue;
}
.modalMain {
padding: 10px;
}
.close {
position: absolute;
top: 10px;
right: 10px;
}
</style>
</head>
<body>
<button class="modal">modal popup</button>
<section class="modalWrapper">
<div class="modalBody">
<header>
<div class="h2">Title</div>
<button class="close">close</button>
</header>
<div class="modalMain">
<p>default main content</p>
</div>
<footer>Modal Footer</footer>
</div>
</section>
<script>
const btn = document.querySelectorAll(".modal");
const modalWrapper = document.querySelector(".modalWrapper");
const body = document.querySelector("body");
btn.forEach(function (button) {
makeClick(button);
})
function makeClick(el) {
el.addEventListener("click", function () {
modalWrapper.classList.add("showModal");
const closeButton = document.querySelector(".close");
closeButton.addEventListener("click",function(){
return modalWrapper.classList.remove("showModal");
})
modalWrapper.addEventListener("click",function(){
return modalWrapper.classList.remove("showModal");
})
body.addEventListener("keydown",function(e){
console.log(e.keyCode);
if(e.keyCode === 27){
return modalWrapper.classList.remove("showModal");
}
})
})
}
</script>
</body>
</html>