Posis

[JavaScript] 여러 개 모달창 닫기 본문

JavaScript

[JavaScript] 여러 개 모달창 닫기

CooNiHong 2021. 10. 19. 04:59

이번 포스팅은 여러 개 모달창 또는 대화상자같은 창들을 원하는 순서대로 제거하는 것을 구현해보겠습니다.

완성된 화면

HTML

<!doctype html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
  <link rel="stylesheet" href="./main.css">
</head>
<body>

<div class="container">
  <div class="alert-box">
    <p>Alert1</p>
    <button class="close">X</button>
  </div>
  <div class="alert-box">
    <p>Alert2</p>
    <button class="close">X</button>
  </div>
  <div class="alert-box">
    <p>Alert3</p>
    <button class="close">X</button>
  </div>
  <div class="alert-box">
    <p>Alert4</p>
    <button class="close">X</button>
  </div>
</div>

</body>
</html>

CSS

.alert-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  border-radius: 8px;
  height: 80px;
  padding: 20px;
  box-sizing: border-box;
}
.alert-box:nth-of-type(1) {
  background: indianred;
}
.alert-box:nth-of-type(2) {
  background: royalblue;
}
.alert-box:nth-of-type(3) {
  background: lightpink;
}
.alert-box:nth-of-type(4) {
  background: yellowgreen;
}
.alert-box p {
  margin: 0;
  font-size: 20px;
  color: #fff;
}

JavaScript

HTML, CSS는 복사한 후에 JavaScript를 한번 구현해보시고 코드를 확인해 보시는 것을 추천드립니다.

더보기
const close = document.querySelectorAll('.close');

close.forEach((item) => {
  item.addEventListener('click', () => {
  	item.parentNode.style.display = 'none';
  })
})

구현 방법

1. 닫기 버튼의 요소를 뽑아옵니다.

2. 몇번째 버튼인지를 알아내기 위해서 forEach를 활용해서 찾는다.

3. 버튼의 부모요소를 display = none해서 화면에서 제거한다.

 

코드만보면 몇줄되지 않기떄문에 매우 간단해 보이지만 막상 구현해보라고 던져주면 생각보다 시간이 걸리게 되는 경우가 생길 수 있다. 간단한 예제들을 풀면서 생각한게 저는 아직도 JavaScript의 기초가 부족하다는 것을 느꼈습니다. 

잘못된 부분이 있거나 피드백할 사항이 있다면 댓글 부탁드립니다!! 구독도 클릭한번 부탁드립니다!!

728x90