모달

모달 (Modal)

Bootstrap의 JavaScript 모달 플러그인을 사용해 라이트박스, 사용자 알림, 또는 완전히 커스텀 콘텐츠를 위한 다이얼로그를 사이트에 추가합니다.

출처: 문서

본문

동작 방식 (How it works)

Bootstrap의 모달 컴포넌트를 시작하기 전에, 최근 메뉴 옵션이 변경되었으니 다음을 꼭 읽어보세요.

  • 모달은 HTML, CSS, JavaScript로 만들어집니다. 문서의 다른 모든 것 위에 배치되며, 모달 콘텐츠가 대신 스크롤되도록 <body>에서 스크롤을 제거합니다.
  • 모달 "백드롭(backdrop)"을 클릭하면 모달이 자동으로 닫힙니다.
  • Bootstrap은 한 번에 하나의 모달 창만 지원합니다. 중첩 모달은 좋지 않은 사용자 경험이라고 생각하므로 지원하지 않습니다.
  • 모달은 position: fixed를 사용하는데, 가끔 렌더링이 까다로울 수 있습니다. 가능하면 모달 HTML을 최상위 위치에 배치해 다른 요소들의 방해 가능성을 피하세요. .modal을 다른 fixed 요소 안에 중첩하면 문제가 생길 가능성이 높습니다.
  • 다시 한 번, position: fixed 때문에 모바일 기기에서 모달을 사용할 때 몇 가지 주의사항이 있습니다. 자세한 내용은 브라우저 지원 문서를 참고하세요.
  • HTML5가 의미론을 정의하는 방식 때문에, autofocus HTML 속성은 Bootstrap 모달에서 아무 효과가 없습니다. 같은 효과를 얻으려면 커스텀 JavaScript를 사용하세요:
const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', () => {
  myInput.focus()
})

이 컴포넌트의 애니메이션 효과는 prefers-reduced-motion 미디어 쿼리에 의존합니다. 저희 접근성 문서의 reduced motion 섹션을 참고하세요.

데모와 사용 가이드를 계속 읽어보세요.

예제 (Examples)

모달 컴포넌트 (Modal components)

아래는 정적(static) 모달 예제입니다 (그 위치와 display가 덮어쓰여 있음). 모달 헤더, 모달 본문(패딩에 필요), 모달 푸터(선택)가 포함되어 있습니다. 가능하면 dismiss 동작이 있는 모달 헤더를 포함하거나, 명시적인 다른 dismiss 동작을 제공하시기 바랍니다.

<div class="modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

위 정적 예제에서 저희는 문서 페이지의 제목 계층 문제를 피하기 위해 <h5>를 사용합니다. 그러나 구조적으로 모달 다이얼로그는 별도의 문서/맥락을 나타내므로, .modal-title은 이상적으로 <h1>이어야 합니다. 필요하다면 글꼴 크기 유틸리티로 제목의 외형을 제어할 수 있습니다. 뒤따르는 모든 라이브 예제는 이 방식을 사용합니다.

라이브 데모 (Live demo)

아래 버튼을 클릭해 동작하는 모달 데모를 토글하세요. 페이지 위쪽에서 슬라이드 다운되며 페이드 인됩니다.

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

정적 백드롭 (Static backdrop)

backdrop이 static으로 설정되면 모달은 바깥을 클릭해도 닫히지 않습니다. 아래 버튼을 클릭해 직접 확인해 보세요.

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>

긴 콘텐츠 스크롤 (Scrolling long content)

모달이 사용자의 뷰포트나 기기에 비해 너무 길어지면, 페이지와 별개로 스크롤됩니다. 아래 데모를 통해 확인해 보세요.

모달에 min-height를 설정하는 인라인 스타일을 사용해 전체 모달의 길이를 늘려 오버플로 스크롤을 보여줍니다. 콘텐츠가 뷰포트 높이보다 길어지면 스크롤이 필요에 따라 모달을 이동합니다.

.modal-dialog에 .modal-dialog-scrollable을 추가하면 모달 본문을 스크롤할 수 있는 스크롤 가능한 모달도 만들 수 있습니다.

<!-- Scrollable modal -->
<div class="modal-dialog modal-dialog-scrollable">
  ...
</div>

세로 중앙 정렬 (Vertically centered)

.modal-dialog에 .modal-dialog-centered를 추가해 모달을 세로로 가운데 정렬합니다.

<!-- Vertically centered modal -->
<div class="modal-dialog modal-dialog-centered">
  ...
</div>

<!-- Vertically centered scrollable modal -->
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
  ...
</div>

툴팁과 팝오버 (Tooltips and popovers)

툴팁과 팝오버는 필요에 따라 모달 안에 배치할 수 있습니다. 모달이 닫히면 그 안의 모든 툴팁과 팝오버도 자동으로 해제됩니다.

<div class="modal-body">
  <h2 class="fs-5">Popover in a modal</h2>
  <p>This <button class="btn btn-secondary" data-bs-toggle="popover" title="Popover title" data-bs-content="Popover body content is set in this attribute.">button</button> triggers a popover on click.</p>
  <hr>
  <h2 class="fs-5">Tooltips in a modal</h2>
  <p><a href="#" data-bs-toggle="tooltip" title="Tooltip">This link</a> and <a href="#" data-bs-toggle="tooltip" title="Tooltip">that link</a> have tooltips on hover.</p>
</div>

그리드 사용 (Using the grid)

.modal-body 안에 .container-fluid를 중첩해 모달 안에서 Bootstrap 그리드 시스템을 활용하세요. 그런 다음 다른 곳에서 하듯 일반 그리드 시스템 클래스를 사용하면 됩니다.

<div class="modal-body">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4">.col-md-4</div>
      <div class="col-md-4 ms-auto">.col-md-4 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-md-3 ms-auto">.col-md-3 .ms-auto</div>
      <div class="col-md-2 ms-auto">.col-md-2 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-md-6 ms-auto">.col-md-6 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-sm-9">
        Level 1: .col-sm-9
        <div class="row">
          <div class="col-8 col-sm-6">
            Level 2: .col-8 .col-sm-6
          </div>
          <div class="col-4 col-sm-6">
            Level 2: .col-4 .col-sm-6
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

모달 콘텐츠 변형 (Varying modal content)

약간 다른 콘텐츠로 같은 모달을 트리거하는 버튼이 많으신가요? event.relatedTarget과 HTML data-bs-* 속성을 사용해 어떤 버튼이 클릭되었는지에 따라 모달의 콘텐츠를 달라지게 하세요.

아래는 라이브 데모와 예제 HTML/JavaScript입니다. 자세한 내용은 relatedTarget에 관한 모달 이벤트 문서를 읽어보세요.

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@mdo">Open modal for @mdo</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@fat">Open modal for @fat</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@getbootstrap">Open modal for @getbootstrap</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">New message</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form>
          <div class="mb-3">
            <label for="recipient-name" class="col-form-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="mb-3">
            <label for="message-text" class="col-form-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
    </div>
  </div>
</div>
const exampleModal = document.getElementById('exampleModal')
if (exampleModal) {
  exampleModal.addEventListener('show.bs.modal', event => {
    // Button that triggered the modal
    const button = event.relatedTarget
    // Extract info from data-bs-* attributes
    const recipient = button.getAttribute('data-bs-whatever')
    // If necessary, you could initiate an Ajax request here
    // and then do the updating in a callback.

    // Update the modal's content.
    const modalTitle = exampleModal.querySelector('.modal-title')
    const modalBodyInput = exampleModal.querySelector('.modal-body input')

    modalTitle.textContent = `New message to ${recipient}`
    modalBodyInput.value = recipient
  })
}

모달 사이 토글 (Toggle between modals)

data-bs-target과 data-bs-toggle 속성의 영리한 배치로 여러 모달 사이를 토글하세요. 예를 들어 이미 열린 로그인 모달 안에서 비밀번호 재설정 모달을 토글할 수 있습니다. 여러 모달이 동시에 열릴 수는 없다는 점을 유의하세요—이 메서드는 단순히 두 개의 별도 모달 사이를 토글할 뿐입니다.

<div class="modal fade" id="exampleModalToggle" aria-hidden="true" aria-labelledby="exampleModalToggleLabel" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalToggleLabel">Modal 1</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Show a second modal and hide this one with the button below.
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" data-bs-target="#exampleModalToggle2" data-bs-toggle="modal">Open second modal</button>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel2" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalToggleLabel2">Modal 2</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Hide this modal and show the first with the button below.
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Back to first</button>
      </div>
    </div>
  </div>
</div>
<button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Open first modal</button>

애니메이션 변경 (Change animation)

$modal-fade-transform 변수는 모달 페이드 인 애니메이션 전의 .modal-dialog의 transform 상태를 결정하고, $modal-show-transform 변수는 모달 페이드 인 애니메이션 끝의 .modal-dialog의 transform을 결정합니다.

예를 들어 줌인(zoom-in) 애니메이션을 원한다면 $modal-fade-transform: scale(.8)을 설정할 수 있습니다.

애니메이션 제거 (Remove animation)

페이드 인 대신 그냥 나타나는 모달을 원한다면 모달 마크업에서 .fade 클래스를 제거하세요.

<div class="modal" tabindex="-1" aria-labelledby="..." aria-hidden="true">
  ...
</div>

동적 높이 (Dynamic heights)

열려 있는 동안 모달의 높이가 변하면, 스크롤바가 나타날 경우를 대비해 myModal.handleUpdate()를 호출해 모달의 위치를 다시 조정해야 합니다.

접근성 (Accessibility)

.modal에 모달 제목을 참조하는 aria-labelledby="..."를 꼭 추가하세요. 추가로 .modal에 aria-describedby로 모달 다이얼로그에 대한 설명을 줄 수도 있습니다. 저희가 JavaScript로 이미 role="dialog"를 추가하므로 직접 추가할 필요는 없습니다.

YouTube 동영상 임베드 (Embedding YouTube videos)

모달에 YouTube 동영상을 임베드하려면 재생을 자동으로 중지하는 등의 Bootstrap에 없는 추가 JavaScript가 필요합니다. 자세한 내용은 이 도움이 되는 Stack Overflow 게시물을 참고하세요.

선택적 크기 (Optional sizes)

모달에는 세 가지 선택적 크기가 있으며, .modal-dialog에 배치하는 변형 클래스로 제공됩니다. 이 크기는 특정 브레이크포인트에서 발동해 더 좁은 뷰포트에 가로 스크롤바가 생기지 않게 합니다.

크기 클래스 모달 최대 너비
Small .modal-sm 300px
Default None 500px
Large .modal-lg 800px
Extra large .modal-xl 1140px

변형 클래스가 없는 기본 모달이 "medium" 크기 모달을 구성합니다.

<div class="modal-dialog modal-xl">...</div>
<div class="modal-dialog modal-lg">...</div>
<div class="modal-dialog modal-sm">...</div>

전체 화면 모달 (Fullscreen Modal)

또 다른 오버라이드로 사용자 뷰포트를 덮는 모달을 팝업하는 옵션이 있습니다. .modal-dialog에 배치하는 변형 클래스로 제공됩니다.

클래스 사용 가능
.modal-fullscreen 항상
.modal-fullscreen-sm-down 576px
.modal-fullscreen-md-down 768px
.modal-fullscreen-lg-down 992px
.modal-fullscreen-xl-down 1200px
.modal-fullscreen-xxl-down 1400px
<!-- Full screen modal -->
<div class="modal-dialog modal-fullscreen-sm-down">
  ...
</div>

CSS

변수 (Variables) — v5.2.0에서 추가

Bootstrap의 진화하는 CSS 변수 접근 방식에 따라, 모달은 이제 .modal과 .modal-backdrop에 로컬 CSS 변수를 사용해 실시간 커스터마이징을 강화합니다. CSS 변수의 값은 Sass를 통해 설정되므로 Sass 커스터마이징도 여전히 지원됩니다.

--#{$prefix}modal-zindex: #{$zindex-modal};
--#{$prefix}modal-width: #{$modal-md};
--#{$prefix}modal-padding: #{$modal-inner-padding};
--#{$prefix}modal-margin: #{$modal-dialog-margin};
--#{$prefix}modal-color: #{$modal-content-color};
--#{$prefix}modal-bg: #{$modal-content-bg};
--#{$prefix}modal-border-color: #{$modal-content-border-color};
--#{$prefix}modal-border-width: #{$modal-content-border-width};
--#{$prefix}modal-border-radius: #{$modal-content-border-radius};
--#{$prefix}modal-box-shadow: #{$modal-content-box-shadow-xs};
--#{$prefix}modal-inner-border-radius: #{$modal-content-inner-border-radius};
--#{$prefix}modal-header-padding-x: #{$modal-header-padding-x};
--#{$prefix}modal-header-padding-y: #{$modal-header-padding-y};
--#{$prefix}modal-header-padding: #{$modal-header-padding}; // Todo in v6: Split this padding into x and y
--#{$prefix}modal-header-border-color: #{$modal-header-border-color};
--#{$prefix}modal-header-border-width: #{$modal-header-border-width};
--#{$prefix}modal-title-line-height: #{$modal-title-line-height};
--#{$prefix}modal-footer-gap: #{$modal-footer-margin-between};
--#{$prefix}modal-footer-bg: #{$modal-footer-bg};
--#{$prefix}modal-footer-border-color: #{$modal-footer-border-color};
--#{$prefix}modal-footer-border-width: #{$modal-footer-border-width};
--#{$prefix}backdrop-zindex: #{$zindex-modal-backdrop};
--#{$prefix}backdrop-bg: #{$modal-backdrop-bg};
--#{$prefix}backdrop-opacity: #{$modal-backdrop-opacity};

Sass 변수 (Sass variables)

$modal-inner-padding:               $spacer;

$modal-footer-margin-between:       .5rem;

$modal-dialog-margin:               .5rem;
$modal-dialog-margin-y-sm-up:       1.75rem;

$modal-title-line-height:           $line-height-base;

$modal-content-color:               var(--#{$prefix}body-color);
$modal-content-bg:                  var(--#{$prefix}body-bg);
$modal-content-border-color:        var(--#{$prefix}border-color-translucent);
$modal-content-border-width:        var(--#{$prefix}border-width);
$modal-content-border-radius:       var(--#{$prefix}border-radius-lg);
$modal-content-inner-border-radius: subtract($modal-content-border-radius, $modal-content-border-width);
$modal-content-box-shadow-xs:       var(--#{$prefix}box-shadow-sm);
$modal-content-box-shadow-sm-up:    var(--#{$prefix}box-shadow);

$modal-backdrop-bg:                 $black;
$modal-backdrop-opacity:            .5;

$modal-header-border-color:         var(--#{$prefix}border-color);
$modal-header-border-width:         $modal-content-border-width;
$modal-header-padding-y:            $modal-inner-padding;
$modal-header-padding-x:            $modal-inner-padding;
$modal-header-padding:              $modal-header-padding-y $modal-header-padding-x; // Keep this for backwards compatibility

$modal-footer-bg:                   null;
$modal-footer-border-color:         $modal-header-border-color;
$modal-footer-border-width:         $modal-header-border-width;

$modal-sm:                          300px;
$modal-md:                          500px;
$modal-lg:                          800px;
$modal-xl:                          1140px;

$modal-fade-transform:              translate(0, -50px);
$modal-show-transform:              none;
$modal-transition:                  transform .3s ease-out;
$modal-scale-transform:             scale(1.02);

Sass 루프 (Sass loops)

반응형 전체 화면 모달은 $breakpoints 맵과 scss/_modal.scss의 루프로 생성됩니다.

@each $breakpoint in map-keys($grid-breakpoints) {
  $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
  $postfix: if($infix != "", $infix + "-down", "");

  @include media-breakpoint-down($breakpoint) {
    .modal-fullscreen#{$postfix} {
      width: 100vw;
      max-width: none;
      height: 100%;
      margin: 0;

      .modal-content {
        height: 100%;
        border: 0;
        @include border-radius(0);
      }

      .modal-header,
      .modal-footer {
        @include border-radius(0);
      }

      .modal-body {
        overflow-y: auto;
      }
    }
  }
}

사용법 (Usage)

모달 플러그인은 데이터 속성이나 JavaScript를 통해 숨겨진 콘텐츠를 요청에 따라 토글합니다. 또한 기본 스크롤 동작을 재정의하고, 모달 바깥을 클릭할 때 표시된 모달을 해제할 클릭 영역을 제공하는 .modal-backdrop을 생성합니다.

데이터 속성으로 (Via data attributes)

토글 (Toggle)

JavaScript를 작성하지 않고 모달을 활성화하세요. 버튼 같은 컨트롤러 요소에 data-bs-toggle="modal"을 설정하고, 토글할 특정 모달을 타깃하기 위해 data-bs-target="#foo" 또는 href="#foo"를 함께 설정하세요.

<button type="button" data-bs-toggle="modal" data-bs-target="#myModal">Launch modal</button>

해제 (Dismiss)

아래처럼 모달 안의 버튼에 data-bs-dismiss 속성을 사용해 해제를 수행할 수 있습니다.

<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

또는 아래처럼 추가 data-bs-target을 사용해 모달 바깥의 버튼에서 수행할 수 있습니다.

<button type="button" class="btn-close" data-bs-dismiss="modal" data-bs-target="#my-modal" aria-label="Close"></button>

모달을 해제하는 두 방식 모두 지원되지만, 모달 바깥에서 해제하는 것은 ARIA Authoring Practices Guide의 dialog(modal) 패턴과 일치하지 않는다는 점을 유의하세요. 감수하고 사용하세요.

JavaScript로 (Via JavaScript)

한 줄의 JavaScript로 모달을 만듭니다:

const myModal = new bootstrap.Modal(document.getElementById('myModal'), options)
// or
const myModalAlternative = new bootstrap.Modal('#myModal', options)

옵션 (Options)

옵션은 데이터 속성이나 JavaScript로 전달할 수 있으므로 data-bs-animation="{value}"처럼 data-bs-에 옵션 이름을 붙일 수 있습니다. 데이터 속성으로 옵션을 전달할 때는 옵션 이름의 표기(camelCase)를 "kebab-case"로 바꿔야 합니다. 예를 들어 data-bs-customClass="beautifier" 대신 data-bs-custom-class="beautifier"를 사용하세요.

Bootstrap 5.2.0부터 모든 컴포넌트는 간단한 컴포넌트 설정을 JSON 문자열로 담을 수 있는 실험적 예약 데이터 속성 data-bs-config를 지원합니다. 요소에 data-bs-config='{"delay":0, "title":123}'과 data-bs-title="456" 속성이 있으면 최종 title 값은 456이 되고, 별도의 데이터 속성이 data-bs-config에 주어진 값을 덮어씁니다. 또한 기존 데이터 속성이 data-bs-delay='{"show":0,"hide":150}'처럼 JSON 값을 담을 수 있습니다.

최종 설정 객체는 data-bs-config, data-bs-, js 객체를 병합한 결과로, 가장 나중에 주어진 키-값이 다른 것들을 덮어씁니다.

이름 타입 기본값 설명
backdrop boolean, 'static' true modal-backdrop 요소를 포함합니다. 또는 static을 지정하면 클릭해도 모달을 닫지 않는 백드롭을 갖습니다.
focus boolean true 초기화할 때 포커스를 모달에 둡니다.
keyboard boolean true escape 키를 누르면 모달을 닫습니다.

메서드 (Methods)

모든 API 메서드는 비동기이며 전환을 시작합니다. 전환이 시작되자마자, 즉 끝나기 전에 호출자에게 반환됩니다. 또한 전환 중인 컴포넌트에 대한 메서드 호출은 무시됩니다. 자세한 내용은 JavaScript 문서를 참고하세요.

옵션 전달 (Passing options)

콘텐츠를 모달로 활성화합니다. 선택적 options 객체를 받습니다.

const myModal = new bootstrap.Modal('#myModal', {
  keyboard: false
})
메서드 설명
dispose 요소의 모달을 파괴합니다. (DOM 요소에 저장된 데이터를 제거합니다.)
getInstance DOM 요소에 연결된 모달 인스턴스를 가져올 수 있는 정적 메서드입니다.
getOrCreateInstance DOM 요소에 연결된 모달 인스턴스를 가져오거나, 초기화되지 않았다면 새로 만드는 정적 메서드입니다.
handleUpdate 열려 있는 동안 모달의 높이가 변하면(즉 스크롤바가 나타날 경우) 모달의 위치를 수동으로 다시 조정합니다.
hide 모달을 수동으로 숨깁니다. 모달이 실제로 숨겨지기 전에(즉, hidden.bs.modal 이벤트가 발생하기 전에) 호출자에게 반환됩니다.
show 모달을 수동으로 엽니다. 모달이 실제로 보이기 전에(즉, shown.bs.modal 이벤트가 발생하기 전에) 호출자에게 반환됩니다. 또한 모달 이벤트에서(relatedTarget 속성으로) 받을 수 있는 DOM 요소를 인자로 전달할 수 있습니다. (즉 const modalToggle = document.getElementById('toggleMyModal'); myModal.show(modalToggle).
toggle 모달을 수동으로 토글합니다. 모달이 실제로 보이거나 숨겨지기 전에(즉, shown.bs.modal 또는 hidden.bs.modal 이벤트가 발생하기 전에) 호출자에게 반환됩니다.

이벤트 (Events)

Bootstrap의 모달 클래스는 모달 기능에 훅을 걸기 위한 몇 가지 이벤트를 노출합니다. 모든 모달 이벤트는 모달 자체에서(즉 <div class="modal">에서) 발생합니다.

이벤트 설명
hide.bs.modal hide 인스턴스 메서드가 호출되는 즉시 발생합니다. event.preventDefault()를 호출해 방지할 수 있습니다. 이벤트 방지에 대한 자세한 내용은 JavaScript 이벤트 문서를 참고하세요.
hidden.bs.modal 모달이 사용자에게 숨겨지기 완료되었을 때 발생합니다 (CSS 전환이 완료될 때까지 기다립니다).
hidePrevented.bs.modal 모달이 표시되고 그 백드롭이 static이며 모달 바깥을 클릭했을 때 발생합니다. 이 이벤트는 escape 키가 눌렸고 keyboard 옵션이 false로 설정된 경우에도 발생합니다.
show.bs.modal show 인스턴스 메서드가 호출되는 즉시 발생합니다. 클릭으로 인한 것이라면 클릭된 요소가 이벤트의 relatedTarget 속성으로 제공됩니다.
shown.bs.modal 모달이 사용자에게 보이게 되었을 때 발생합니다 (CSS 전환이 완료될 때까지 기다립니다). 클릭으로 인한 것이라면 클릭된 요소가 이벤트의 relatedTarget 속성으로 제공됩니다.
const myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', event => {
  // do something...
})

더 알아보기 (Learn more)