본문 바로가기

프론트엔드/자바스크립트

모달 (Modal)

반응형
 

웹 프로그래밍에서 팝업 또는 dialog 창을 모달 (modal)이라고 합니다. 모달의 가장 큰 특징은 유저의 관심을 특정 액션에 집중시키는 데 있는데요. HTML, CSS, JavaScript를 활용해서 모달을 만드는 방법을 알아보겠습니다.

 


 

구현 방법

먼저, HTML 코드부터 보겠습니다. (해당 기능에 집중하기 위해 불필요한 코드는 생략)

 

HTML 파일의 본문 안에 모달 요소를 넣습니다.

<!-- index.html -->

<body>
  <button id="auth">auth</button>
  
  <div class="modal">
    <form>
      <i id="close">❌</i>
    </form>
  </div>  
</body>

CSS로 모달을 화면의 흐름에서 제외시킵니다. position: absolute; 또는 position: fixed;로 구현 가능한데 저는 본문 내용의 길이와 관계없이 언제나 화면 전체를 가릴 수 있는 position: fixed; 선호합니다. 그리고 속성을 사용하여 모달 요소를 숨기면 되는데 여기서는 간단한 구현을 위해 display: none;을 선택했습니다.

.modal {
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;  
  background-color: rgba(0, 0, 0, .3);
  display: none;
  align-items: center;
  justify-content: center;
}

form {
  height: 300px;
  width: 300px;
  background-color: aliceblue;
  position: relative;
}

i {
  position: absolute;
  top: 5px;
  right: 10px;
  cursor: pointer;
}

마지막으로 자바스크립트에서 아래와 같이 클릭이벤트를 구현하면 완성됩니다.

const auth = document.getElementById('auth')
const modal = document.querySelector('.modal')
const close = document.getElementById('close')

// opens modal
auth.addEventListener('click', () => {
  modal.style.display = 'flex'
})

// closes modal when X icon is clicked
close.addEventListener('click', () => {
  modal.style.display = 'none'
})

// closes modal when anywhere outside the modal form is clicked
modal.addEventListener('click', (e) => {
  modal.style.display = 'none'
})

모달을 구현하는 많은 방법 중 제가 즐겨 사용하는 방법을 소개해 드렸는데요. 개인적으로는 모달의 단순함과 명료함 때문에 자주 사용합니다.


참조

 

How To Make a Modal Box With CSS and JavaScript

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

 

What Is a Modal and When Should I Use One?

Learn how to effectively and strategically place modal windows on your website to capture attention and prompt action from visitors.

blog.hubspot.com

728x90
반응형

'프론트엔드 > 자바스크립트' 카테고리의 다른 글

웹팩 (webpack)  (0) 2022.12.21
Declarative Code VS Imperative Code  (0) 2022.12.21
데이터 요청  (0) 2022.12.17
자바스크립트로 주간 / 야간 모드 바꾸기  (0) 2022.12.16
무한스크롤 (infinite scrolling)  (0) 2022.12.02