[Vanilla JS] Modal 창 만들기

2021. 5. 31. 16:40·JavaScript
반응형

Vanilla js Modal

[ HTML ] 

<button>Open Modal</button>
  <div class="modal hidden">
    <div class="modal__background"></div>
    <div class="modal__content">
      <h1>--Modal--</h1>
      <button>Close</button>
    </div>
  </div>

Open Modal 버튼을 눌렀을 때 Modal이 나오도록 할 것이다.

background는 modal창 배경 부분을 나타내고 content는 modal 창 내부를 나타낸다.

 

 

[ CSS ]

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
}

button {
  all: unset;
  background-color: mediumslateblue;
  color: white;
  padding: 5px 25px;
  border-radius: 10px;
  cursor: pointer;
}
.btn {
  margin-top: 60px;
}

.modal {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.modal__background {
  background-color: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  position: absolute;
}

.modal__content {
  text-align: center;
  position: relative;
  background-color: white;
  border-radius: 10px;
  top: 0;
  padding: 10px 25px;
  width: 20%;
}

h1 {
  margin: 0;
  margin-bottom: 13px;
}

.hidden {
  display: none;
}

 

 

[ JavaScript ]

const openButton = document.querySelector("button");
const modal = document.querySelector(".modal");
const closeButton = modal.querySelector("button");
const modalBackground = modal.querySelector(".modal__background");

function displayModal(){
    modal.classList.toggle("hidden");
}

openButton.addEventListener("click", displayModal);
closeButton.addEventListener("click", displayModal)
modalBackground.addEventListener("click", displayModal);

Modal 창이 열렸을 때 background 클릭하여도 닫히게 만들었다.

 

 

[ 결과 ]

See the Pen VanillaJs-Modal by 신성철 (@pugoxjbx-the-animator) on CodePen.

반응형
'JavaScript' 카테고리의 다른 글
  • [Javascript] HTML에 Font Awesome 아이콘 출력하기
  • [Vanilla JS] Menu 만들기
  • [Vanilla JS] Drag & Drop 만들기
  • [Vanilla JS] Slider 만들기
꾸매코더
꾸매코더
웹 / 앱 개발자
  • 꾸매코더
    꾸매코딩
    꾸매코더
  • 전체
    오늘
    어제
    • 분류 전체보기 (96)
      • JavaScript (18)
        • Deep Dive (0)
      • React (5)
      • React-Native (9)
      • CSS (3)
      • TypeScript (1)
      • CS (10)
      • GitHub (4)
      • Clone Coding (15)
        • Kakaotalk [HTML + CSS] (10)
        • Momentum [JavaScript] (5)
      • Project (30)
        • Timer Project (14)
        • Netflix [React + Hooks] (12)
        • ToDoList [React-Native] (4)
      • 회고 (1)
  • 링크

    • Github
  • hELLO· Designed By정상우.v4.10.3
꾸매코더
[Vanilla JS] Modal 창 만들기
상단으로

티스토리툴바