Programming Language/🟨 Javascript
바닐라 JS로 Modal 만들기
DarrenKwonDev
2020. 4. 18. 04:50
기본 아이디어는, hidden 클래스를 추가하거나 뺌으로써 모달창을 보여주거나 닫는 것이다. position이 조금 tricky하긴 하지만 딱히 어렵지는 않다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
button {
all: unset;
background-color: steelblue;
color: white;
padding: 15px 40px;
border-radius: 10px;
cursor: pointer;
}
.modal {
position: fixed;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.modal__overlay {
position: absolute;
background-color: rgba(0, 0, 0, 0.6);
width: 100%;
height: 100%;
}
.modal__content {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
align-items: center;
background-color: white;
padding: 15px;
border-radius: 15px;
top: 0;
width: 30%;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
}
.hidden {
display: none;
}
</style>
</head>
<body>
<button class="modalButton">Open Modal</button>
<div class="modal hidden">
<div class="modal__overlay"></div>
<div class="modal__content">
<h2>I'm a modal</h2>
<button class="closeModal">close</button>
</div>
</div>
<script>
const modalButton = document.querySelector(".modalButton");
const modal = document.querySelector(".modal");
const closeModal = document.querySelector(".closeModal");
const modal__overlay = document.querySelector(".modal__overlay");
modalButton.addEventListener("click", () => {
modal.classList.remove("hidden");
});
closeModal.addEventListener("click", () => {
modal.classList.add("hidden");
});
modal__overlay.addEventListener("click", () => {
modal.classList.add("hidden");
});
</script>
</body>
</html>