Modal

모달(Modal)은 페이지 위에 겹쳐 떠 있는 대화상자 컴포넌트예요. 사용자에게 중요한 정보를 보여주거나 선택을 요구할 때 사용합니다. 팝업처럼 보이지만 사용자 상호작용을 차단하는 특성이 있어요.

출처: 문서

본문

Types

Modal

표준 모달이에요.

$('.ui.modal')
        .modal('show')
      ;
      
      
        
          
          
            Profile Picture
          
          
            
              
            
            
              We've auto-chosen a profile image for you.
              
              
            
          
          
            
              Nope
            
            
              Yep, that's me

Basic

모달은 복잡성을 줄일 수 있어요.

$('.ui.basic.modal')
        .modal('show')
      ;
      
      
        
          
            
            Archive Old Messages
          
          
            
          
          
            
              
              No
            
            
              
              Yes

Content

Header

모달은 헤더를 가질 수 있어요.

Header

Content

모달은 콘텐츠를 포함할 수 있어요.

Header

Image Content

모달은 이미지 콘텐츠를 포함할 수 있어요.

Header

Actions

모달은 액션 행을 포함할 수 있어요.

Header
          
            
          
          
            Approve
            Neutral
            Cancel

Variations

Full Screen

모달은 화면 전체 크기를 사용할 수 있어요.

$('.fullscreen.modal')
        .modal('show')
      ;

Overlay Full Screen

모달은 화면 전체를 덮을 수 있어요.

$('.overlay.fullscreen.modal')
      .modal('show')
      ;

Size

모달은 크기가 달라질 수 있어요.

$('.mini.modal')
        .modal('show')
      ;
      
      
      $('.tiny.modal')
        .modal('show')
      ;
      
      
      $('.small.modal')
        .modal('show')
      ;
      
      
      $('.large.modal')
        .modal('show')
      ;

Inverted

모달은 흰 dimmer 위에 inverted로 표시될 수 있어요...

$('.mini.inverted.modal')
        .modal({
           inverted: true
        })
        .modal('show')
      ;
      
        
      
      $('.mini.inverted.modal')
        .modal('show')
      ;

Scrolling Content

모달은 스크롤되는 콘텐츠를 가질 수 있어요.

You can also use resizable scrolling content and a native resize drag handler will appear to the bottom right of the content. This needs a modern browser, so does not work in IE11 or legacy Edge.
      
        
          Header
          
            
          
        
        
      
      $('.ui.longer.modal')
        .modal('show')
      ;

크기 조절 가능한 스크롤 콘텐츠를 사용할 수도 있으며, 네이티브 크기 조절 드래그 핸들러가 콘텐츠의 오른쪽 아래에 나타나요. 이 기능은 최신 브라우저가 필요하므로 IE11이나 레거시 Edge에서는 동작하지 않아요.

Center Aligned

헤더, 콘텐츠, 심지어 액션도 각각 중앙 정렬할 수 있어요.

Header is centered
              
                  
              
              
                  Cancel
                  OK
              
          
      
      
          $('#centerexample')
          .modal('show')
          ;

Left Actions

액션 버튼을 왼쪽에 배치할 수도 있어요.

Look at the Actions
            
              
            
              
                  Cancel
                  OK
              
          
      
      
          $('#leftactionsexample')
          .modal('show')
          ;

Basic Header and Actions

헤더 및/또는 액션은 콘텐츠와 같은 기본(basic) 배경에 나타날 수도 있어요.

Basic Header
              
                
              
              
                  Cancel
                  OK
              
          
      
      
          $('#basicheaderactionsexample')
          .modal('show')
          ;

States

Active

활성 모달은 페이지에 표시돼요.

Examples

Disabling Vertical Centering

모달의 콘텐츠가 동적이거나 여러 단계로 구성되어 있다면, 세로 중앙 정렬을 비활성화해서 높이가 변할 때 콘텐츠가 세로로 점프하지 않게 하는 것이 좋을 수 있어요.

$('.special.modal')
        .modal({
          centered: false
        })
        .modal('show')
      ;

Top or Bottom aligned

centered 옵션을 기본값 true로 두어도, 모달 자체에 top aligned(centered:false와 동일) 또는 bottom aligned 클래스를 추가해 모달 위치를 강제할 수 있어요.

$('.bottom.aligned.modal')
          .modal('show')
          ;

Scrolling Modal

모달 콘텐츠가 브라우저 높이를 초과하면, 아래 페이지를 스크롤하지 않고 스크롤에 딱 맞는 공간만 추가되도록 스크롤 가능 영역이 자동으로 확장돼요.

$('.long.modal')
        .modal('show')
      ;

Internally Scrolling Content

모달 콘텐츠가 스스로 스크롤되게 하고 싶다면 scrolling content 변형을 사용할 수 있어요.

You can also use resizable scrolling content and a native resize drag handler will appear to the bottom right of the content. This needs a modern browser, so does not work in IE11 or legacy Edge.
      
      $('.longer.modal')
        .modal('show')
      ;

Multiple Modals

모달은 두 번째 모달을 열 수 있어요. allowMultiple: true 매개변수를 사용하면 두 번째 모달이 첫 번째 모달 위에 열려요. 그렇지 않으면 두 번째 모달이 열리기 전에 첫 번째 모달이 닫혀요.

// initialize all modals
      $('.coupled.modal')
        .modal({
          allowMultiple: true
        })
      ;
      // open second modal on first modal buttons
      $('.second.modal')
        .modal('attach events', '.first.modal .button')
      ;
      // show first immediately
      $('.first.modal')
        .modal('show')
      ;
      
      
      $('.coupled.modal')
        .modal({
          allowMultiple: false
        })
      ;
      // attach events to buttons
      $('.second.modal')
        .modal('attach events', '.first.modal .button')
      ;
      // show first now
      $('.first.modal')
        .modal('show')
      ;

Forcing a Choice

모달의 dimmer가 클릭으로 닫히지 않게 해서 사용자가 선택을 하도록 강제할 수 있어요.

$('.basic.test.modal')
        .modal('setting', 'closable', false)
        .modal('show')
      ;

Approve / Deny Callbacks

모달은 approve/deny 콜백을 positive/approve, negative/deny 또는 ok/cancel 버튼에 자동으로 연결해요.

$('.ui.basic.test.modal')
        .modal({
          closable  : false,
          onDeny    : function(){
            window.alert('Wait not yet!');
            return false;
          },
          onApprove : function() {
            window.alert('Approved!');
          }
        })
        .modal('show')
      ;

Attach events

모달은 다른 요소에 이벤트를 연결할 수 있어요.

$('.test.modal')
        .modal('attach events', '.test.button', 'show')
      ;
      
      Launch modal

Transitions

모달은 어떤 명명된 ui transition도 사용할 수 있어요.

Choose transition
        
        
          Horizontal Flip
          Vertical Flip
          Fade Up
          Fade
          Scale
        
      
      
      
      $('.selection.dropdown')
        .dropdown({
          onChange: function(value) {
            $('.test.modal')
              .modal('setting', 'transition', value)
              .modal('show')
            ;
          }
        })
      ;

Dimmer Variations

모달은 dimmer가 어떻게 표시될지 조정하는 blurring이나 inverted 같은 추가 변형을 지정할 수 있어요.

$('.ui.modal')
        .modal({
          inverted: true
        })
        .modal('show')
      ;
      
      
      $('.ui.modal')
        .modal({
          blurring: true
        })
        .modal('show')
      ;

Initializing a modal

Via Javascript properties

마크업을 직접 만들 필요 없이 임시 모달을 만들 수 있어요. 임시 모달은 커스텀 onHidden 콜백이 주어지지 않으면 기본적으로 닫힐 때 DOM에서 제거돼요.

$.modal({
          title: 'Important Notice',
          class: 'mini',
          closeIcon: true,
          content: 'You will be logged out in 5 Minutes',
          actions: [{
            text: 'Alright, got it',
            class: 'green'
          }]
      }).modal('show');

Via existing DOM node

모달은 페이지 어디에나 포함될 수 있어요. 초기화 시 모달의 현재 크기가 캐시되고, 요소는 DOM에서 분리되어 dimmer 안으로 이동해요.

Why move modal content?
        
        
      
      
      $('.ui.modal')
        .modal()
      ;
      
      
        
          
          
            Modal Title
          
          
            
              An image can appear on left or an icon
            
            
              A description can appear on the right
            
          
          
            Cancel
            OK
          
        
      

      
        Usually a given close icon on smaller modals will be displayed outside of the modal.
        You can force to display the close icon inside the modal, just like in fullscreen modals, by adding the inside class to the close icon.

보통 작은 모달의 닫기 아이콘은 모달 바깥에 표시돼요. 닫기 아이콘에 inside 클래스를 추가하면 fullscreen 모달처럼 모달 안에 표시하도록 강제할 수 있어요.

Reuse existing modal with new content

모달 마크업을 일반 템플릿으로 준비해 그 일반적인 스타일은 재사용하되, 실제 콘텐츠는 js 속성으로 제공할 수 있어요.

var now = new Date();now.setDate(now.getDate()+Math.floor(Math.random() * 31 + 1));
        $('#reusemodal').modal({
          title: 'Free voucher until '+now.toDateString(),
          content: 'Your voucher code is'+Math.random().toString(16).substr(2).toUpperCase()+'',
          classContent: 'centered',
          class: 'small'
        }).modal('show');
      
      
        
            
            
            
                Redeem now
                Not now

Behavior

다음 모든 행동들은 다음 구문을 사용해 호출할 수 있어요:

.ui.modal')
      .modal('behavior name', argumentOne, argumentTwo)
    ;
행동 설명
show 모달을 보여줘요.
hide 모달을 숨겨요.
toggle 모달을 토글해요.
refresh 페이지에서 모달의 중앙 정렬을 새로고침해요.
show dimmer 연관된 페이지 dimmer를 보여줘요.
hide dimmer 연관된 페이지 dimmer를 숨겨요.
hide others dimmer 안에서 선택된 모달이 아닌 모든 모달을 숨겨요.
hide all 같은 dimmer 안의 보이는 모든 모달을 숨겨요.
cache sizes 현재 모달 크기를 캐시해요.
can fit 모달이 페이지에 맞을 수 있는지 반환해요.
is active 모달이 활성인지 반환해요.
set active 모달을 활성으로 설정해요.
destroy 인스턴스를 파괴하고 모든 이벤트를 제거해요.

Config Templates

config template은 미리 구성된 임시 모달을 즉시 표시하는 특별한 행동이에요. 세 가지 기본 템플릿이 포함되어 있어요: alert, confirm, prompt. 기존 바닐라 JS 변형과 동등하지만, 모양과 느낌을 더 다양하게 커스터마이즈할 수 있어요.

config template 모달은 항상 자동 표시(autoShow)되므로 수동 show는 필요 없어요.

$.modal('alert','hello')
      $.modal('confirm','Are you sure?',function(value){})
      $.modal('prompt','Enter Code', function(value){})

Alert

가능한 매개변수는 title, content, handler (바닐라 js 사용과 거의 동일하게 유지하기 위해 이 순서로) 또는 객체 {title:'',content:'',handler:function(){}}로, title과 content는 HTML을 포함할 수 있어요.

If you don't trust the content set the global modal setting for preserveHTML to false.
      
          $.modal('alert','hello');
      
      
          $.modal('alert','Watch out','This is an important message!');
      
      
         $.modal('alert',{
            title: 'Listen to me',
            content: 'I love Fomantic-UI',
            handler: function() {
              $.toast({message:'Great!'});
            }
          });

콘텐츠를 신뢰하지 않는다면 전역 modal 설정 preserveHTML을 false로 설정하세요.

Confirm

매개변수 목록과 로직은 alert와 동일해요. 선택된 boolean 값이 주어진 콜백 핸들러에 제공돼요.

// title and content
        $.modal('confirm','Attention!','Ready?');
      
      
      // title, content and handler
        $.modal('confirm','Attention!','Ready?', function(choice){
          $.toast({message:'You '+ (choice ? 'Accepted':'Declined')});
        });
      
      
      // content and handler
        $.modal('confirm','Ready?', function(choice){
          $.toast({message:'You '+ (choice ? 'Accepted':'Declined')});
        });
      
      
      // title and handler
        $.modal('confirm',{
          title: 'Ready?',
          handler: function(choice){
            $.toast({message:'You '+ (choice ? 'Accepted':'Declined')});
          }
        });

Prompt

prompt 호출은 기본적으로 alert와 confirm과 동일해요. 객체가 주어질 때 사용 가능한 옵션이 두 개 더 있어요: placeholder와 defaultValue. 콘텐츠용 HTML 코드를 제공하고 그 안에 input이 있다면 그 input이 입력 필드로 사용되며, 그렇지 않으면 동적으로 생성해줘요.

// provide a placeholder
    $.modal('prompt',{
      title: 'Enter your name',
      placeholder: 'Do not enter your mothers name!',
      handler: function(name){
          $.toast({message: 'Your name is ' + (name || 'CANCELLED')});
      }
    });
      
      
  // set a defaultValue
    $.modal('prompt',{
      title: 'Enter your name',
      defaultValue: 'mommy',
      handler: function(name){
          $.toast({message: 'Your name is ' + (name || 'CANCELLED')});
      }
    });
      
      
  // custom input
    $.modal('prompt', 'Custom Input', 'Nickname', function(name) {
      $.toast({message: 'Your name is ' + (name || 'CANCELLED')});
    });

Create your own template

modals 템플릿 객체를 한 번 확장하면 자신만의 커스텀 config 템플릿을 정의할 수 있어요. 모달을 생성/표시하기 전에 모달 설정에 병합될 객체를 반환해야 해요.

$.fn.modal.settings.templates.greet = function(username) {
  // do something according to modals settings and/or given parameters
    var settings = this.get.settings(); // "this" is the modal instance
    return {
      title: 'Greetings to ' + username + '!',
      content: ''+ username.toUpperCase() + 'is the best!',
      class: 'inverted',
      classContent: 'centered',
      dimmerSettings: {
        variation: 'inverted'
      }
    }
  }
      
      
      
          $.modal('greet','mom')
      
      
          $.modal('greet','dad')

Settings

Modal 설정은 모달의 동작을 수정해요.

설정 기본값 설명
detachable true false로 설정하면 모달이 dimmer 안으로 이동하는 것을 방지해요.
useFlex 'auto' auto는 flex 컨테이너 안에서 절대 배치 요소를 지원하는 브라우저에서 자동으로 flex를 사용해요. true/false로 설정하면 모든 브라우저에 그 설정을 강제해요.
autofocus true true일 때 모달 안의 첫 폼 입력이 표시될 때 포커스를 받아요. false로 설정하면 이 동작을 막을 수 있어요.
restoreFocus true false일 때 모달이 숨길 때 모달 표시 전 마지막 포커스된 요소에 다시 포커스하지 않아요. 모달을 닫은 후 원치 않는 스크롤 동작을 방지할 수 있어요.
autoShow false true일 때 인스턴스 생성 시 즉시 모달을 보여줘요.
observeChanges false modal DOM의 어떤 변경이 캐시된 위치를 자동으로 새로고침할지 여부예요.
allowMultiple false true로 설정하면 새 모달을 열 때 다른 보이는 모달을 닫지 않아요.
inverted false inverted dimmer를 사용할지 여부예요.
blurring false dimmer가 배경을 흐리게 할지 여부예요.
centered true 모달이 중앙 정렬되어야 할지 여부예요.
keyboardShortcuts true 키보드 단축키를 자동으로 바인딩할지 여부예요. ESC 키를 누르면 모달을 닫아요.
offset 0 닫기 버튼처럼 모달 바깥의 콘텐츠가 중앙에 오도록 할 세로 오프셋이에요.
context body 어둡게 할 영역을 지정하는 선택자 또는 jQuery 객체예요.
closable true false로 설정하면 dimmer를 클릭해 모달을 닫을 수 없게 돼요.
dimmerSettings { closable : false, useCSS : true } UI dimmer를 확장하는 커스텀 설정을 지정할 수 있어요.
transition scale 메뉴를 애니메이션할 때 사용할 명명된 트랜지션이에요. 전체 목록은 ui transitions 문서에서 찾을 수 있어요. 또는 객체를 제공해 hide/show 트랜지션과 hide/show 시간을 개별 값으로 설정할 수 있어요.
duration 400 애니메이션 시간이에요. transition 설정을 통해 개별 hide/show 시간 값을 제공하면 이 값은 무시돼요.
queue false 추가 애니메이션이 대기열에 쌓일지 여부예요.
scrollbarWidth 10 webkit 커스텀 스크롤바가 클릭됐는지 확인해 dimmer 숨김을 방지하기 위해 내부적으로 사용돼요. 다른 테마를 사용 중이라면 site.less의 @customScrollbarWidth에 정의된 (숫자) 값과 동일하게 설정해야 해요.

Callbacks

Callbacks는 특정 행동 이후 발생할 함수를 지정해요.

콜백 컨텍스트 설명
onShow Modal 모달이 표시되기 시작할 때 호출돼요. 함수가 false를 반환하면 모달이 표시되지 않아요.
onVisible Modal 모달의 표시 애니메이션이 끝난 후 호출돼요.
onHide($element) Modal 모달이 숨겨지기 시작한 후 호출돼요. 함수가 false를 반환하면 모달이 숨겨지지 않아요.
onHidden Modal 모달의 숨김 애니메이션이 끝난 후 호출돼요.
onApprove($element) Click positive/approve/ok 버튼을 누른 후 호출돼요. 함수가 false를 반환하면 모달이 숨겨지지 않아요.
onDeny($element) Modal negative/deny/cancel 버튼을 누른 후 호출돼요. 함수가 false를 반환하면 모달이 숨겨지지 않아요.

DOM Settings

DOM 설정은 이 모듈이 DOM과 어떻게 인터페이스할지 지정해요.

selector    : {
        title    : '> .header',
        content  : '> .content',
        actions  : '> .actions',
        close    : '> .close',
        approve  : '.actions .positive, .actions .approve, .actions .ok',
        deny     : '.actions .negative, .actions .deny, .actions .cancel',
        dimmer   : '> .ui.dimmer',
        bodyFixed: '> .ui.fixed.menu, > .ui.right.toast-container, > .ui.right.sidebar, > .ui.fixed.nag, > .ui.fixed.nag > .close',
        prompt   : '.ui.input > input'
      }
  • namespace — modal. 이벤트 네임스페이스예요.
  • selector — 모듈의 부분을 찾는 데 사용되는 선택자예요.
  • className — 요소 상태를 결정하는 데 사용되는 클래스 이름이에요: active, animating, blurring, inverted, legacy, loading, scrolling, undetached, front, close(close icon), button(ui button), modal(ui modal), title(header), content, actions, template(ui tiny modal), ok(positive), cancel(negative), prompt(ui fluid input), innerDimmer(ui inverted dimmer).

Config Template Settings

Config Template 설정은 동적으로 생성된 모달의 기본 콘텐츠를 정의해요.

설정 기본값 설명
title '' 모달 헤더의 콘텐츠.
content '' 모달 콘텐츠의 콘텐츠.
closeIcon false 모달이 닫기 아이콘을 포함할지 여부.
actions false 객체 배열. 각 객체는 text, class, icon, click 속성으로 액션을 정의해요. 액션은 기본적으로 모달을 닫아요. click 핸들러에서 false를 반환하면 그 동작을 막을 수 있어요. class 속성에 approve (approve, ok, positive)나 deny (deny, cancel, negative) 클래스 이름을 사용하면 click 핸들러는 무시돼요. 그런 경우 onApprove/onDeny 콜백을 사용하세요.
preserveHTML true 주어진 title/content/actions에 포함된 HTML을 보존할지 여부. 신뢰할 수 없는 3rd party 콘텐츠를 다룰 때는 false로 설정.
class / classTitle / classContent / classActions '' modal/title/content/actions 클래스에 추가되어 모양을 제어하는 문자열.
fields { class:'class', text:'text', icon:'icon', click:'click' } 액션 객체의 속성 필드 매핑.
text { ok:'Ok', cancel:'Cancel' } 기본 버튼 텍스트.

Debug Settings

Debug 설정은 콘솔에 대한 디버그 출력을 제어해요.

설정 기본값 설명
name Modal 디버그 로그에 사용되는 이름.
silent false 모든 콘솔 출력을 조용히 만들어요.
debug false 콘솔에 표준 디버그 출력.
performance true 콘솔에 표준 디버그 출력.
verbose false 콘솔에 보조 디버그 출력.
error { dimmer:'UI Dimmer, a required component is not included in this page', method:'The method you called is not defined.', notFound:'The element you specified could not be found' } 오류 메시지 설정.

더 알아보기 (Learn more)

모달로 알림·확인·입력 프롬프트까지 간단히 만들 수 있어요. $.modal('alert') 같은 config 템플릿을 활용하면 마크업 없이도 빠르게 UI를 띄울 수 있어요. 배경을 어둡게 하는 원리와 콘텐츠 표시 방식은 Dimmer와 Flyout 문서도 함께 참고하세요.