꾸매코딩

[Vanilla JS] Modal 창 만들기 본문

JavaScript

[Vanilla JS] Modal 창 만들기

꾸매코더 2021. 5. 31. 16:40
반응형

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.

반응형