본문 바로가기
Programming/JavaScript

JavaScript 모달 구조와 구현 방법

by d-e-v-j 2025. 1. 7.
반응형

모달은 사용자와의 상호작용을 위해 화면 위에 나타나는 대화 상자이다. 모달은 특정 작업이나 알림을 제공하거나 추가정보를 표시하기 위해 사용된다. 일반적으로 모달은 배경을 어둡게 만들어 사용자의 시선을 집중시키며, 주요작업을 완료하거나 닫을때까지 상호작용이 제한된다.

 

1. 모달의 주요 구성 요소

  • 오버레이: 모달이 열렸을 때 배경을 어둡게 만들어 사용자 시선을 모달로 집중시킨다.
  • 모달 컨테이너: 모달의 내용을 담는 박스로, 텍스트 ,버튼, 이미지 등을 포함할 수 있다
  • 닫기: 사용자가 모달을 닫을 수 있다.

 

2. 기본적인 구조

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>기본 모달 예제</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <!-- 모달을 여는 버튼 -->
  <button id="showModalButton">모달 열기</button>

  <!-- 모달 오버레이 -->
  <div id="modalOverlay">
    <div id="modalContainer">
      <div id="modalContent">
        <p>이것은 모달의 내용입니다.</p>
        <button id="closeModalButton">닫기</button>
      </div>
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>

 

CSS

/* 전체 화면 오버레이 */
#modalOverlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none; /* 기본적으로 숨김 */
  justify-content: center;
  align-items: center;
}

/* 모달 컨테이너 */
#modalContainer {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  text-align: center;
  width: 300px;
}

/* 닫기 버튼 */
#closeModalButton {
  margin-top: 10px;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background: #f44336;
  color: white;
  font-size: 14px;
}

/* 모달 열기 버튼 */
#showModalButton {
  padding: 10px 15px;
  background: #0f55d9;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

 

JavaScript

// 모달 관련 요소 가져오기
const showModalButton = document.getElementById('showModalButton');
const modalOverlay = document.getElementById('modalOverlay');
const closeModalButton = document.getElementById('closeModalButton');

// 모달 열기
showModalButton.addEventListener('click', () => {
  modalOverlay.style.display = 'flex';
});

// 모달 닫기
closeModalButton.addEventListener('click', () => {
  modalOverlay.style.display = 'none';
});

// 오버레이 클릭 시 모달 닫기
modalOverlay.addEventListener('click', (e) => {
  if (e.target === modalOverlay) {
    modalOverlay.style.display = 'none';
  }
});

 

모달은 웹 애플리케이션에서 중요한 UI 요소중 하나로 최근데 팝업을 대체하여 많이 사용되고 있다.

728x90
반응형
LIST