Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

CSS와 JavaScript로 삭제 확인 모달(Modal) 만드는 방법

웹 애플리케이션에서 사용자가 계정 삭제처럼 되돌릴 수 없는 중요한 작업을 수행하기 전에 한 번 더 확인받는 것은 매우 중요합니다. 이때 활용되는 것이 바로 삭제 확인 모달(Modal)입니다. 별도의 라이브러리 없이 CSS와 JavaScript만으로도 손쉽게 만들 수 있으며, 아래 전체 예제 코드를 통해 그 방법을 자세히 살펴보겠습니다.

전체 코드 예제

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
    body {
        font-family: Arial, Helvetica, sans-serif;
    }
    .modal {
        text-align: center;
        display: none;
        position: fixed;
        z-index: 1;
        padding-top: 100px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.4);
    }
    .modalContent {
        font-size: 20px;
        font-weight: bold;
        background-color: #fefefe;
        margin: auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
    }
    .close {
        color: rgb(255, 65, 65);
        float: right;
        font-size: 40px;
        font-weight: bold;
    }
    .close:hover, .close:focus {
        color: #ff1010;
        cursor: pointer;
    }
    .modalContent button {
        border: none;
        border-radius: 4px;
        font-size: 18px;
        font-weight: bold;
        padding: 10px;
    }
    .del {
        background-color: rgb(255, 65, 65);
    }
    .del:hover {
        background-color: rgb(255, 7, 7);
    }
    .cancel:hover {
        background-color: rgb(167, 167, 167);
    }
</style>
</head>
<body>
<h1>Modal Example</h1>
<button class="openModal">Open Modal</button>
<h2>Click on the above button to open modal</h2>
<div class="modal">
<div class="modalContent">
<span class="close">×</span>
<p>Are you sure you want to delete your account</p>
<button class="del" onclick="hideModal()">Delete Account</button>
<button class="cancel" onclick="hideModal()">Cancel</button>
</div>
</div>
<script>
    var modal = document.querySelector(".modal");
    var btn = document.querySelector(".openModal");
    var span = document.querySelector(".close");
    btn.addEventListener("click", () => {
        modal.style.display = "block";
    });
    span.addEventListener("click", () => {
        hideModal();
    });
    function hideModal() {
        modal.style.display = "none";
    }
    window.onclick = function(event) {
        if (event.target == modal) {
            hideModal();
        }
    };
</script>
</body>
</html>

실행 결과

위 코드를 브라우저에서 실행하면 다음과 같은 초기 화면이 나타납니다.

CSS와 JavaScript로 삭제 확인 모달(Modal) 만드는 방법

화면의 Open Modal 버튼을 클릭하면 아래와 같이 배경이 어두워지면서 삭제 확인 모달 창이 중앙에 표시됩니다.

CSS와 JavaScript로 삭제 확인 모달(Modal) 만드는 방법

코드 동작 원리

1. HTML 구조

모달은 두 개의 div로 구성됩니다. 외부의 .modal은 화면 전체를 덮는 반투명 오버레이 역할을 하고, 내부의 .modalContent는 실제 메시지와 버튼이 담기는 흰색 콘텐츠 영역입니다. 오른쪽 상단의 ×(.close) 버튼으로도 모달을 닫을 수 있습니다.

2. CSS 스타일링

.modal에는 position: fixed;z-index: 1;을 적용해 모달이 항상 화면 최상위에 고정되도록 했습니다. 또한 display: none;으로 기본적으로 숨겨두고, rgba(0, 0, 0, 0.4) 배경색으로 뒤쪽 콘텐츠를 어둡게 처리하여 사용자의 시선을 모달에 집중시킵니다.

3. JavaScript 동작

Open Modal 버튼을 클릭하면 addEventListener가 등록된 이벤트 리스너가 모달의 display 값을 block으로 변경해 모달을 화면에 표시합니다. 반대로 ×버튼, Delete Account 버튼, Cancel 버튼을 클릭하거나 모달 바깥의 어두운 배경 영역을 클릭하면 hideModal() 함수가 호출되어 display 값이 none으로 설정되고 모달이 사라집니다.

이처럼 CSS와 JavaScript만으로도 사용자 경험을 높이는 삭제 확인 모달을 간단하게 구현할 수 있습니다. 실제 프로젝트에서는 Delete Account 버튼 클릭 시 실제 삭제 로직(API 호출 등)을 연결하고, Cancel 버튼에는 별도의 동작을 지정하는 방식으로 확장할 수 있습니다.