Skip to content

jQuery UI 치트시트

jQuery 기반의 엄선된 사용자 인터페이스 인터랙션과 위젯 모음입니다.

01

시작하기

CDN 설치

jQuery UI는 jQuery 코어에 의존합니다 — 항상 jquery-ui.js 전에 jQuery를 로드하세요. CSS는 기본 테마를 제공하며 Datepicker와 Dialog 같은 위젯이 올바르게 표시되려면 필수입니다. 1.13.x 버전은 jQuery 1.8+를 지원합니다.

jquery-ui
<!-- jQuery UI requires jQuery core first -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

npm 설치

npm으로 설치하면 필요한 위젯만 임포트해 트리 셰이킹할 수 있습니다(예: jquery-ui/ui/widgets/datepicker). 전체 'jquery-ui' 번들을 임포트하면 모든 위젯과 이펙트가 포함됩니다. CSS 테마는 별도로 임포트해야 합니다.

jquery-ui
# Install via npm
npm install jquery jquery-ui

# Import in your bundle
import $ from "jquery";
import "jquery-ui/ui/widgets/datepicker";
import "jquery-ui/themes/base/all.css";

// Or import the full bundle
import "jquery-ui";

기본 위젯 초기화

모든 jQuery UI 위젯은 같은 플러그인 패턴을 따릅니다: $(selector).widgetName(options). 설정에는 옵션 객체를 전달하고, 메서드는 문자열 문법('methodName', args...)으로 호출합니다. 초기화는 항상 $(function(){})으로 감싸거나 스크립트를 body 끝에 두세요.

jquery-ui
$(function () {
  // Initialize a widget on a selector
  $("#datepicker").datepicker();
  $("#dialog").dialog();

  // Pass options as an object
  $("#accordion").accordion({
    active: false,
    collapsible: true,
  });

  // Get or set an option after init
  $("#accordion").accordion("option", "active", 1);
});

위젯 메서드 패턴

문자열 기반 API가 모든 위젯에서 일관됩니다. 'option' 게터/세터, 'enable'/'disable', 'widget'(가장 바깥 요소 반환), 'destroy'(원래 마크업 복원)가 모든 위젯이 지원합니다. 요소를 제거할 때 메모리 누수를 피하려 destroy를 쓰세요.

jquery-ui
// All widgets share the same API conventions
$("#dialog").dialog("open");              // call a method
$("#dialog").dialog("option", "title");   // get an option
$("#dialog").dialog("option", "modal", true); // set an option
$("#dialog").dialog("disable");           // disable widget
$("#dialog").dialog("enable");            // enable widget
$("#dialog").dialog("widget");            // get the wrapper element
$("#dialog").dialog("destroy");           // remove widget entirely

테마 설정

jQuery UI는 약 24개의 미리 만든 테마를 제공합니다. 'base' 테마가 기본입니다. ThemeRoller(themroller.jqueryui.com)가 커스텀 테마를 생성합니다. .ui-widget-header나 .ui-state-default 같은 특정 클래스를 오버라이드하려면 자신의 CSS를 base 뒤에 로드하세요.

jquery-ui
<!-- Default base theme -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">

<!-- Other bundled themes: ui-lightness, ui-darkness, smoothness, redmond, ... -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">

<!-- Override theme with your own CSS -->
<link rel="stylesheet" href="jquery-ui.css">
<link rel="stylesheet" href="my-theme-overrides.css">

클래스 네이밍 관례

CSS 프레임워크는 일관된 ui-* 네이밍 관례를 씁니다. 인터랙션 상태(default, hover, active, focus)가 위젯이 자동으로 적용합니다. jQuery UI 스타일과 어울리도록 자신의 마크업에서 이 클래스들을 직접 쓸 수 있습니다.

jquery-ui
/* jQuery UI CSS classes are namespaced with ui- */
.ui-widget         /* base widget class */
.ui-widget-header  /* header bar (accordion, datepicker) */
.ui-widget-content /* content area */
.ui-state-default  /* default interactive state */
.ui-state-hover    /* mouse-over state */
.ui-state-active   /* active/selected state */
.ui-state-focus    /* keyboard focus state */
.ui-state-disabled /* disabled state */
.ui-corner-all     /* rounded corners (themable) */
.ui-icon           /* base icon class */
02

Draggable

기본 Draggable

요소를 드래그 가능하게 만드는 것은 한 번의 호출입니다. 그러면 마우스로 요소를 옮길 수 있습니다. ui-widget-content 클래스가 기본 테마 스타일을 적용합니다. Draggable이 위치를 상속합니다 — 필요에 따라 relative/absolute가 적용됩니다.

jquery-ui
<!-- HTML -->
<div id="box" class="ui-widget-content" style="width:100px;height:100px;">
  Drag me
</div>

<!-- JS -->
<script>
  $(function () {
    $("#box").draggable();
  });
</script>

Draggable 옵션

옵션이 드래그 동작을 제어합니다. 'axis'가 이동을 한 축으로 제한하고, 'containment'가 드래그 영역을 제한하며, 'grid'가 간격에 스냅하고, 'revert'가 요소를 시작 위치로 돌려보냅니다. 'helper: clone'은 원본 대신 복사본을 드래그합니다.

jquery-ui
$("#box").draggable({
  axis: "x",              // constrain to x or y axis
  containment: "parent",  // or "window", "document", or selector
  cursor: "move",         // cursor while dragging
  cursorAt: { left: 5 },  // offset cursor from drag handle
  grid: [20, 20],         // snap to grid
  delay: 100,             // ms delay before drag starts
  distance: 5,            // px before drag starts
  revert: true,           // snap back to start
  revertDuration: 200,    // revert animation duration
  scroll: false,          // prevent auto-scroll
  helper: "clone",        // "original", "clone", or function
  opacity: 0.6,           // opacity while dragging
  zIndex: 1000,           // z-index while dragging
});

드래그 이벤트

드래그 중 세 이벤트가 발생합니다: 'start'(시작 시 한 번), 'drag'(이동 중 계속), 'stop'(끝에 한 번). ui 객체가 position(부모 기준)과 offset(페이지 기준)을 제공합니다. 'drag'에서 무거운 작업은 성능을 해칩니다.

jquery-ui
$("#box").draggable({
  start: function (event, ui) {
    console.log("Drag started", ui.position);
  },
  drag: function (event, ui) {
    // Fires continuously during drag
    console.log(ui.position.left, ui.position.top);
  },
  stop: function (event, ui) {
    console.log("Drag stopped at", ui.position);
    console.log("Offset:", ui.offset);
  },
});

Handle & Cancel

'handle'은 드래그 시작을 특정 자식 요소로 제한합니다 — 박스 전체가 움직여야 하지만 제목 표시줄을 통해서만 움직이게 할 때 유용. 'cancel'은 편집에 마우스 상호작용이 필요한 input이나 textarea 같은 요소에서 드래그를 막습니다.

jquery-ui
<!-- Only the header acts as the drag handle -->
<div id="box" class="ui-widget-content">
  <div class="drag-handle">Drag from here</div>
  <div class="content">Some content here</div>
  <textarea>Editable content</textarea>
</div>

<script>
  $("#box").draggable({
    handle: ".drag-handle",   // only this starts the drag
    cancel: "textarea",       // these elements never start a drag
  });
</script>

이동 제한

containment가 요소를 드래그할 수 있는 곳을 제한합니다. 'parent', 'window', 'document', 선택자, 명시적 [x1,y1,x2,y2] 배열 모두 동작합니다. 'grid'와 결합하면 레이아웃 에디터나 대시보드를 위한 정밀하고 스냅된 배치를 만들 수 있습니다.

jquery-ui
// Constrain within a parent element
$("#box").draggable({ containment: "parent" });

// Constrain within the window
$("#box").draggable({ containment: "window" });

// Constrain within a specific selector
$("#box").draggable({ containment: "#drag-area" });

// Constrain to an explicit bounding box [x1, y1, x2, y2]
$("#box").draggable({ containment: [0, 0, 500, 300] });

// Snap to a 50px grid
$("#box").draggable({ grid: [50, 50] });

요소에 스냅

'snap'은 충분히 가까우면 드래그 요소가 대상 요소와 정렬되게 점프합니다. 'snapMode'가 정렬을 제어합니다: 'inner'(대상 안쪽), 'outer'(대상 바깥), 'both'. 요소가 정렬되어야 하는 다이어그램 도구나 대시보드 레이아웃에 유용합니다.

jquery-ui
$(".card").draggable({
  snap: ".snap-target",     // selector of elements to snap to
  snapMode: "inner",        // "inner", "outer", or "both"
  snapTolerance: 30,        // px distance to trigger snap
});

// Snap to all siblings of the same class
$(".card").draggable({
  snap: ".card",
  snapTolerance: 20,
});
03

Droppable

기본 Droppable

Droppable이 드래그된 요소를 받아들이는 대상 영역을 정의합니다. 드래그 요소가 그 위에서 놓이면 'drop' 콜백이 발생합니다. ui.draggable 프로퍼티가 드래그된 요소의 참조를 줘 이동하거나 처리할 수 있습니다.

jquery-ui
<div id="draggable" class="ui-widget-content">Drag me</div>
<div id="droppable" class="ui-widget-header">Drop here</div>

<script>
  $(function () {
    $("#draggable").draggable();
    $("#droppable").droppable({
      drop: function (event, ui) {
        $(this).addClass("ui-state-highlight")
               .html("Dropped!");
      },
    });
  });
</script>

Droppable 옵션

'accept'가 어떤 드래그 요소가 허용되는지 필터합니다 — 선택자나 함수. 'activeClass'와 'hoverClass'가 시각적 피드백을 제공합니다. 'greedy: true'는 중첩된 droppable이 둘 다 drop 이벤트를 받는 것을 막아 중첩 드롭 존에 유용합니다.

jquery-ui
$("#droppable").droppable({
  accept: ".special",       // only accept matching draggables
  activeClass: "ui-state-default",  // class while a drag is active
  hoverClass: "ui-state-hover",     // class while draggable is over
  tolerance: "fit",         // drop detection mode
  greedy: true,             // stop event propagation
  disabled: false,          // disable the droppable
});

드롭 이벤트

다섯 이벤트가 드롭 라이프사이클 전체를 커버합니다. 'activate'/'deactivate'는 매칭 드래그가 시작/끝날 때 발생합니다. 'over'/'out'은 드래그 요소가 존에 들어가거나 나올 때 발생합니다. 'drop'은 성공적인 놓기에서만 발생합니다. 점진적 시각 피드백에 쓰세요.

jquery-ui
$("#droppable").droppable({
  activate: function (event, ui) {
    // Fires when an accepted draggable starts moving
    $(this).addClass("ui-state-default");
  },
  deactivate: function (event, ui) {
    // Fires when the drag ends (drop or cancel)
    $(this).removeClass("ui-state-default");
  },
  over: function (event, ui) {
    // Draggable entered the drop zone
    $(this).addClass("ui-state-hover");
  },
  out: function (event, ui) {
    // Draggable left the drop zone
    $(this).removeClass("ui-state-hover");
  },
  drop: function (event, ui) {
    // Draggable was released here
    console.log("Dropped:", ui.draggable);
  },
});

accept 선택자

'accept'는 선택자 문자열이나 불리언을 반환하는 함수가 될 수 있습니다. 함수는 드래그된 요소를 받고 후보마다 실행되어, 데이터 속성이나 계산된 상태 같은 런타임 로직을 적용하게 합니다. 수락되지 않은 드래그 요소는 drop 이벤트를 트리거하지 않습니다.

jquery-ui
<!-- HTML: red and blue boxes -->
<div class="red draggable">Red</div>
<div class="blue draggable">Blue</div>

<div id="red-bin" class="bin">Red bin</div>
<div id="blue-bin" class="bin">Blue bin</div>

<script>
  // Only accept elements matching the selector
  $("#red-bin").droppable({ accept: ".red" });
  $("#blue-bin").droppable({ accept: ".blue" });

  // Or use a function for dynamic logic
  $("#any-bin").droppable({
    accept: function (drag) {
      return $(drag).data("category") === "recyclable";
    },
  });
</script>

tolerance 모드

tolerance가 드롭이 인식되기 위해 필요한 겹침 정도를 정의합니다. 'fit'이 가장 엄격합니다(요소 전체가 안쪽). 'pointer'는 마우스 커서 기반입니다. 'intersect'(50% 겹침)가 대부분의 UI에 좋은 균형입니다. 'touch'가 가장 관대합니다.

jquery-ui
$("#droppable").droppable({
  // "fit": draggable must be fully inside (default)
  tolerance: "fit",

  // "intersect": at least 50% overlap
  tolerance: "intersect",

  // "pointer": mouse pointer must be inside
  tolerance: "pointer",

  // "touch": any edge touching counts
  tolerance: "touch",
});

클래스로 시각 피드백

activeClass(수락된 드래그가 진행되는 동안 표시)와 hoverClass(드래그 요소가 존 위에 있을 때 표시)를 결합해 사용자에게 명확한 피드백을 주세요. drop 핸들러에서는 보통 드래그 요소를 append해 드롭 존으로 재부모화합니다.

jquery-ui
<!-- CSS -->
<style>
  .drop-active { border: 2px dashed #ccc; }
  .drop-hover  { border: 2px solid #0a0; background: #efe; }
</style>

<!-- JS -->
$("#zone").droppable({
  accept: ".item",
  activeClass: "drop-active",
  hoverClass: "drop-hover",
  drop: function (event, ui) {
    $(this).append(ui.draggable);
    ui.draggable.css({ top: 0, left: 0 });
  },
});
04

Resizable

기본 Resizable

resizable이 요소에 리사이즈 핸들을 추가합니다. 기본적으로 오른쪽 아래(se) 모서리에 핸들이 나타납니다. 핸들이 올바르게 고정되려면 요소에 positioning(relative/absolute)이 적용되어야 합니다.

jquery-ui
<div id="box" class="ui-widget-content">
  Resize me from the corner
</div>

<script>
  $(function () {
    $("#box").resizable();
  });
</script>

리사이즈 핸들

'handles'가 어떤 모서리/모서리에 리사이즈 그립이 붙을지 제어합니다. 나침반 방향을 쓰세요: n, e, s, w, ne, se, sw, nw. 기본값은 'e, s, se'입니다. 셀렉터로 커스텀 핸들 요소를 제공해 스타일링을 완전히 제어할 수도 있습니다.

jquery-ui
$("#box").resizable({
  handles: "n, e, s, w, ne, se, sw, nw",  // all eight handles
});

// Or specify handle elements
$("#box").resizable({
  handles: {
    n: ".n-handle",
    se: ".se-handle",
  },
});

Resizable 옵션

옵션이 리사이징을 제한하고 커스터마이징합니다. 'aspectRatio'가 비율을 유지합니다(이미지/비디오에 좋음). 'alsoResize'가 다른 요소를 동기화합니다. 'ghost'는 리사이즈 중 흐린 미리보기를 보여주고 실제 크기는 놓을 때 적용합니다. min/max 치수가 경계를 강제합니다.

jquery-ui
$("#box").resizable({
  alsoResize: "#other",     // resize another element in sync
  animate: true,            // animate to final size
  animateDuration: 200,     // ms
  aspectRatio: 16 / 9,      // preserve width:height ratio
  autoHide: true,           // hide handles until hover
  containment: "parent",    // restrict resize within parent
  grid: [10, 10],           // snap to grid
  maxHeight: 400,
  maxWidth: 600,
  minHeight: 100,
  minWidth: 100,
  ghost: true,              // show a ghost outline while resizing
});

리사이즈 이벤트

draggable처럼 resize가 start/resize/stop을 발생시킵니다. ui 객체에는 'size'(width, height)와 'position'(left, top)이 있습니다. 북쪽이나 서쪽 모서리에서 리사이즈하면 크기와 위치가 모두 바뀝니다. 라이브 미리보기 같은 의존 UI 갱신에 resize 이벤트를 쓰세요.

jquery-ui
$("#box").resizable({
  start: function (event, ui) {
    console.log("Resize start", ui.size, ui.position);
  },
  resize: function (event, ui) {
    // Fires continuously during resize
    ui.size.width;   // new width
    ui.size.height;  // new height
    ui.position.left; // new position (may change for n/w handles)
  },
  stop: function (event, ui) {
    console.log("Final size:", ui.size);
  },
});

종횡비 & 제약

이미지와 미디어에는 aspectRatio(숫자 또는 현재 비율 고정의 true)를 쓰세요. min/max 제약과 결합하면 어색한 크기를 막습니다. 그리드 스냅이 간격에 정렬합니다 — 에디터 인터페이스와 레이아웃 도구에 유용합니다.

jquery-ui
// Keep a 4:3 ratio
$("#photo").resizable({ aspectRatio: 4 / 3 });

// Keep ratio and stay within bounds
$("#photo").resizable({
  aspectRatio: 4 / 3,
  maxWidth: 800,
  maxHeight: 600,
  minWidth: 100,
  minHeight: 75,
});

// Snap to a grid of 20px
$("#grid-box").resizable({ grid: [20, 20] });

Animate & Ghost 모드

'animate'는 마우스를 뗀 뒤 새 크기로 부드럽게 전환합니다. 'ghost'는 드래그 중 반투명 미리보기를 보여주고 실제 변화는 놓을 때만 적용합니다. 함께 쓰면 다듬어지고 떨림 없는 리사이즈 경험이 됩니다.

jquery-ui
// Animate to the final size after release
$("#box").resizable({
  animate: true,
  animateDuration: "slow",   // or ms number
  animateEasing: "swing",
});

// Show a ghost outline while dragging, apply on release
$("#box").resizable({
  ghost: true,
  helper: "ui-resizable-helper",  // class for the ghost
});

// Combine both
$("#box").resizable({ ghost: true, animate: true });
05

Selectable

기본 Selectable

selectable이 자식들의 목록을 선택 가능한 그룹으로 만듭니다. 클릭으로 선택하거나 라소를 드래그해 여러 개를 선택하세요. Ctrl/Cmd를 누르면 선택에 추가되고, Shift는 범위를 선택합니다. 선택된 항목은 자동으로 ui-selected 클래스를 얻습니다.

jquery-ui
<ol id="selectable">
  <li class="ui-widget-content">Item 1</li>
  <li class="ui-widget-content">Item 2</li>
  <li class="ui-widget-content">Item 3</li>
</ol>

<script>
  $(function () {
    $("#selectable").selectable();
  });
</script>

Selectable 옵션

'filter'가 어떤 자식이 참여할지 제한합니다. 'tolerance'가 라소 동작을 제어합니다: 'touch'는 겹치기만 하면 선택(기본값), 'fit'은 완전히 포함되어야 합니다. 큰 목록에는 성능 개선을 위해 'autoRefresh: false'를 설정하고 레이아웃 변경 뒤 $(...).selectable('refresh')를 수동 호출하세요.

jquery-ui
$("#selectable").selectable({
  filter: "li",            // which children can be selected
  tolerance: "touch",      // "touch" or "fit" for lasso overlap
  distance: 0,             // px before lasso starts
  delay: 0,                // ms delay before lasso starts
  autoRefresh: true,       // recompute positions on each drag
  disabled: false,
  cancel: "a, .no-select", // elements that never start selection
});

선택 이벤트

이벤트가 선택 라이프사이클 동안 발생합니다: 드래그 중 'selecting'/'unselecting', 확정 시 'selected'/'unselected', 전체 연산에는 'start'/'stop'. 각 ui 객체에 관련 요소가 있습니다(selecting, selected 등).

jquery-ui
$("#selectable").selectable({
  selecting: function (event, ui) {
    // ui.selecting: element being lassoed
    $(ui.selecting).addClass("highlight");
  },
  selected: function (event, ui) {
    // ui.selected: element just confirmed selected
    console.log("Selected:", $(ui.selected).text());
  },
  unselecting: function (event, ui) {
    $(ui.unselecting).removeClass("highlight");
  },
  unselected: function (event, ui) {
    console.log("Unselected:", $(ui.unselected).text());
  },
  start: function (event, ui) { /* lasso started */ },
  stop: function (event, ui) { /* lasso released */ },
});

필터 항목

특정 자식만 선택되게 하려 'filter'를, 제외하려 'cancel'을 쓰세요. 잠금되거나 읽기 전용인 일부 항목이 참여하지 말아야 하는 갤러리에 유용합니다. 라소는 매칭되지 않는 요소를 단순히 무시합니다.

jquery-ui
<ul id="gallery">
  <li class="selectable-item">Photo 1</li>
  <li class="locked">Locked</li>
  <li class="selectable-item">Photo 2</li>
</ul>

<script>
  $("#gallery").selectable({
    filter: ".selectable-item",  // only these can be selected
    cancel: ".locked",            // locked items never select
  });
</script>

선택 항목 스타일링

jQuery UI가 ui-selecting(드래그 중)과 ui-selected(놓은 뒤) 클래스를 자동 적용합니다. 피드백을 주려 이들을 스타일링하세요. 컨테이너 안에서 언제든 $('.ui-selected')로 현재 선택을 읽을 수 있습니다 — 툴바와 대량 작업에 편리합니다.

jquery-ui
/* CSS */
#selectable .ui-selecting {
  background: #feca40;        /* while dragging */
}
#selectable .ui-selected {
  background: #f39814;        /* confirmed selection */
  color: white;
}
#selectable li {
  margin: 3px; padding: 6px;
  border: 1px solid #ccc;
}

/* selected count badge */
function updateCount() {
  var n = $("#selectable .ui-selected").length;
  $("#count").text(n + " selected");
}
$("#selectable").on("selectablestop", updateCount);

프로그래밍 선택

라소 히트 테스트가 정확하게 유지되도록 항목 추가/제거 뒤에 'refresh'를 호출하세요. 내장 'select' 메서드는 없지만 ui-selected 클래스를 수동 토글할 수 있습니다. 모든 항목에서 그 클래스를 제거해 지우세요.

jquery-ui
// Refresh positions after DOM changes
$("#selectable").selectable("refresh");

// Disable / enable
$("#selectable").selectable("disable");
$("#selectable").selectable("enable");

// Remove the widget
$("#selectable").selectable("destroy");

// Manually select an item (set the class)
$("#selectable li").eq(2).addClass("ui-selected");

// Clear all selections
$("#selectable .ui-selected").removeClass("ui-selected");
06

Sortable

기본 Sortable

sortable이 목록 항목을 드래그로 재정렬 가능하게 만듭니다. 드래그 중 항목이 시각적으로 이동하고 놓으면 DOM 순서가 갱신됩니다. 작업 목록, 사진 갤러리, 우선순위 순서 콘텐츠에 유용합니다.

jquery-ui
<ul id="sortable">
  <li class="ui-widget-content">Item 1</li>
  <li class="ui-widget-content">Item 2</li>
  <li class="ui-widget-content">Item 3</li>
</ul>

<script>
  $(function () {
    $("#sortable").sortable();
  });
</script>

Sortable 옵션

옵션이 정렬 동작을 다듬습니다. 'placeholder'가 남겨진 빈 공간을 스타일링하고, forcePlaceholderSize가 항목 치수와 일치시킵니다. 'axis'가 가로/세로로 제한합니다. 'handle'이 드래그 그립을 지정합니다 — 항목 전체에 인터랙티브 자식이 있을 때 이상적입니다.

jquery-ui
$("#sortable").sortable({
  axis: "y",                // constrain to vertical
  cursor: "move",
  handle: ".handle",        // drag from this element only
  placeholder: "sortable-placeholder", // class for the drop preview
  forcePlaceholderSize: true, // match placeholder to item size
  helper: "clone",          // "original" or "clone"
  opacity: 0.7,
  revert: true,             // animate item into place
  tolerance: "pointer",     // "intersect" or "pointer"
  scroll: true,             // auto-scroll the page
  containment: "parent",    // restrict within parent
});

정렬 이벤트

핵심 이벤트: 'start'/'stop'이 정렬을 감쌉니다. 'change'는 드래그 중 항목 위치가 바뀔 때 발생합니다. 'update'는 최종 순서가 시작과 다를 때만 발생합니다 — 새 순서를 영속화하는 자리이며, 보통 순서대로 항목 ID를 반환하는 toArray()를 씁니다.

jquery-ui
$("#sortable").sortable({
  start: function (event, ui) {
    ui.item;            // the dragged element
    ui.placeholder;     // the placeholder element
    ui.helper;          // the helper being dragged
  },
  change: function (event, ui) {
    // Position in list changed during drag
  },
  sort: function (event, ui) {
    // Fires continuously while sorting
  },
  beforeStop: function (event, ui) {
    // Just before the item is placed
  },
  stop: function (event, ui) {
    console.log("Sort ended");
  },
  update: function (event, ui) {
    // Order actually changed — persist it here
    var order = $(this).sortable("toArray");
    saveOrder(order);
  },
});

연결된 리스트

'connectWith'가 여러 sortable을 연결해 항목을 서로 끌어다 놓을 수 있게 합니다 — 칸반 보드나 파이프라인 관리자에 좋습니다. 각 리스트는 여전히 toArray()로 자기 순서를 추적합니다. 리스트 간 전이에 반응하려 receive/remove 이벤트를 쓰세요.

jquery-ui
<ul id="list-a" class="connected">
  <li>Task A1</li><li>Task A2</li>
</ul>
<ul id="list-b" class="connected">
  <li>Task B1</li>
</ul>

<script>
  $(".connected").sortable({
    connectWith: ".connected",  // allow moving between lists
    placeholder: "ui-state-highlight",
  }).disableSelection();
</script>

Placeholder & Helper

플레이스홀더는 항목이 착지할 자리의 빈 공간입니다 — 명확한 드롭 피드백을 주도록 스타일링하세요. 항목 높이가 다양할 때 forcePlaceholderSize가 중요합니다. 커스텀 helper 함수로 드래그 중 단순화된 미리보기를 보여줄 수 있습니다.

jquery-ui
$("#sortable").sortable({
  placeholder: "ui-state-highlight",  // class for the gap
  forcePlaceholderSize: true,
  helper: function (event, el) {
    // Return a custom helper element
    return $("<div class='custom-helper'>Moving...</div>");
  },
  cursorAt: { top: 10, left: 10 },
});

// Use a clone as the helper instead of moving the original
$("#sortable").sortable({ helper: "clone" });

정렬 메서드

toArray()가 현재 순서의 ID를 반환합니다 — 영속화에 가장 유용합니다. serialize()는 ID가 'name_number' 관례를 따를 때 쿼리 문자열을 만듭니다. cancel()이 가장 최근 정렬을 되돌립니다. 프로그래밍 방식으로 항목을 추가한 뒤 refresh()를 호출하세요.

jquery-ui
// Get current order as an array of IDs
var order = $("#sortable").sortable("toArray");
// ["item-1", "item-3", "item-2"]

// Get option values
var placeholder = $("#sortable").sortable("option", "placeholder");

// Serialize items as a query string (uses id="name_number")
var data = $("#sortable").sortable("serialize");
// "item[]=1&item[]=2&item[]=3"

// Cancel the current sort (revert)
$("#sortable").sortable("cancel");

// Refresh positions after DOM changes
$("#sortable").sortable("refresh");

// Disable / enable / destroy
$("#sortable").sortable("disable");
$("#sortable").sortable("enable");
$("#sortable").sortable("destroy");
07

Accordion

기본 Accordion

accordion은 헤더 + 콘텐츠 요소의 쌍을 기대합니다(헤더가 먼저 와야 합니다). 기본적으로 한 번에 하나의 섹션만 열립니다. 기본 헤더 요소는 h3이지만 header 옵션으로 바꿀 수 있습니다. 콘텐츠 패널이 각 헤더를 따릅니다.

jquery-ui
<div id="accordion">
  <h3>Section 1</h3>
  <div>Content for section 1</div>
  <h3>Section 2</h3>
  <div>Content for section 2</div>
  <h3>Section 3</h3>
  <div>Content for section 3</div>
</div>

<script>
  $(function () {
    $("#accordion").accordion();
  });
</script>

Accordion 옵션

모든 패널이 닫히는 것을 허용하려 'collapsible: true'를 설정하세요(기본은 하나가 열려 있음을 강제). 'heightStyle: content'는 각 패널을 콘텐츠 크기로 맞추고, 'fill'은 모든 패널을 컨테이너 높이로, 'auto'는 가장 큰 패널의 높이를 씁니다.

jquery-ui
$("#accordion").accordion({
  active: 0,                 // index of open panel (false = all closed)
  collapsible: true,         // allow closing all panels
  disabled: false,
  animate: 200,              // ms or "ease name" or false
  heightStyle: "content",    // "auto", "fill", or "content"
  header: "h3",              // header selector
  icons: {
    header: "ui-icon-triangle-1-e",
    activeHeader: "ui-icon-triangle-1-s",
  },
  event: "click",            // event that toggles panels
});

Accordion 이벤트

beforeActivate에서 false를 반환하면 패널 변경을 거부할 수 있습니다 — 저장되지 않은 변경 경고에 유용. activate는 애니메이션 완료 후 발생합니다. ui 객체가 두 이벤트 모두에 대해 옛/새 헤더와 패널 요소를 줍니다.

jquery-ui
$("#accordion").accordion({
  beforeActivate: function (event, ui) {
    // ui.oldHeader, ui.oldPanel (closing)
    // ui.newHeader, ui.newPanel (opening)
    // Return false to cancel
    if ($(ui.newHeader).data("locked")) return false;
  },
  activate: function (event, ui) {
    // Fires after a panel finishes opening
    console.log("Opened:", ui.newHeader.text());
  },
  create: function (event, ui) {
    // Fires on initialization
    console.log("Accordion created, open:", ui.header.text());
  },
});

커스텀 아이콘

icons가 닫힘(헤더)과 열림(activeHeader) 아이콘 클래스를 매핑합니다. 아이콘을 끄려 false를 전달하세요. 적절한 클래스 이름을 제공하면 어떤 아이콘 라이브러리(FontAwesome, Material Icons)든 쓸 수 있습니다 — 아이콘 span이 자동 생성됩니다.

jquery-ui
$("#accordion").accordion({
  icons: {
    header: "ui-icon-circle-arrow-e",
    activeHeader: "ui-icon-circle-arrow-s",
  },
});

// Disable icons entirely
$("#accordion").accordion({ icons: false });

// Use your own icon classes (e.g. with FontAwesome)
$("#accordion").accordion({
  icons: {
    header: "fa fa-plus",
    activeHeader: "fa fa-minus",
  },
});

collapsible & 다중 섹션

진짜 '여러 개 동시 열림' 아코디언은 jQuery UI의 accordion이 네이티브로 지원하지 않습니다 — 대신 섹션마다 별개의 collapsible 아코디언을 초기화하거나 tabs를 쓰세요. 'collapsible: true' 옵션은 현재 열린 패널의 닫힘만 허용합니다.

jquery-ui
// Allow all panels to be closed
$("#accordion").accordion({
  collapsible: true,
  active: false,   // start with all closed
});

// Make every section independently toggleable
// (a true multi-open accordion = separate collapsibles)
$(".section").each(function () {
  $(this).accordion({
    collapsible: true,
    active: false,
    header: ".section-header",
  });
});

동적 Accordion

위젯이 재바인딩하도록 패널 추가/제거 뒤에 refresh()를 호출하세요. active 옵션으로 인덱스로 프로그래밍 방식 패널 열림을 할 수 있습니다. beforeActivate 패턴이 처음 열릴 때만 AJAX로 패널 콘텐츠를 지연 로드하는 깔끔한 방법입니다.

jquery-ui
// Refresh after adding content
$("#accordion").append("<h3>New</h3><div>Content</div>");
$("#accordion").accordion("refresh");

// Switch the open panel
$("#accordion").accordion("option", "active", 2);

// Disable / enable
$("#accordion").accordion("disable");
$("#accordion").accordion("enable");

// Destroy
$("#accordion").accordion("destroy");

// Load content on demand (AJAX-style)
$("#accordion").accordion({
  beforeActivate: function (event, ui) {
    var panel = ui.newPanel;
    if (panel.is(":empty")) {
      panel.load("/api/section/" + ui.newHeader.data("id"));
    }
  },
});
08

Autocomplete

기본 Autocomplete

정적 제안에는 'source'에 문자열 배열을 전달하세요. 위젯이 사용자 타이핑에 따라 부분 문자열로 필터합니다. 제안이 드롭다운으로 나타나며 선택하면 input이 채워집니다. 더 풍부한 표시를 위해 목록은 {label, value} 객체를 담을 수도 있습니다.

jquery-ui
<label for="city">City:</label>
<input id="city" type="text">

<script>
  $(function () {
    var cities = ["London", "Paris", "Berlin", "Madrid", "Rome"];
    $("#city").autocomplete({ source: cities });
  });
</script>

원격 데이터 소스

source가 URL이면 autocomplete가 타이핑된 텍스트를 ?term=으로 하는 GET 요청을 보내고 JSON 배열을 기대합니다. minLength가 서버 부하를 줄이기 위해 충분한 문자가 타이핑될 때까지 요청을 미룹니다. delay 옵션이 빠른 타이핑을 디바운스합니다.

jquery-ui
$("#city").autocomplete({
  source: "/api/cities",   // server endpoint
  minLength: 2,            // start suggesting after 2 chars
  delay: 300,              // ms between keystroke and request
});

// The server should return JSON like:
// ["London", "Paris", "Berlin"]
// or [{ "label": "London, UK", "value": "London" }]

Autocomplete 옵션

autoFocus: true는 첫 제안을 하이라이트해 Enter를 누르면 즉시 선택됩니다. position이 jQuery UI Position을 써 input 기준 메뉴 배치를 설정합니다. appendTo는 input이 overflow 문제가 있는 절대 위치 컨테이너 안에 있을 때 유용합니다.

jquery-ui
$("#city").autocomplete({
  source: cities,          // array, URL, or function
  minLength: 1,            // chars before suggestions appear
  delay: 300,              // ms between keystroke and request
  autoFocus: true,         // focus first item automatically
  appendTo: "#container",  // where to render the menu
  position: { my: "left top", at: "left bottom" },
  disabled: false,
});

커스텀 소스 함수

함수 소스가 완전한 제어를 줍니다 — 캐싱, 커스텀 필터링, 여러 엔드포인트 결합에 유용합니다. 비어 있어도 배열로 response(results)를 반드시 호출해야 합니다. 각 항목은 label/value 외 임의의 필드를 가질 수 있으며 select 핸들러에서 접근합니다.

jquery-ui
$("#city").autocomplete({
  source: function (request, response) {
    // request.term is the typed text
    // response() must be called with the results array
    $.getJSON("/api/cities", { q: request.term })
      .done(function (data) {
        response(data);
      })
      .fail(function () {
        response([]);  // always call response, even on error
      });
  },
  select: function (event, ui) {
    // ui.item.label, ui.item.value
    $("#city-id").val(ui.item.id);
  },
});

Autocomplete 이벤트

focus는 사용자가 제안 사이를 이동할 때(키보드나 hover) 발생합니다. select는 항목이 실제로 선택될 때 발생합니다. change는 blur에서 발생하며 최종 값이 소스에 존재하는지 검증하는 적합한 자리입니다. false를 반환하면 기본 input 채우기가 막힙니다.

jquery-ui
$("#city").autocomplete({
  source: cities,
  focus: function (event, ui) {
    // Fires when an item is highlighted (not selected)
    $("#preview").text(ui.item.label);
    return false;  // prevent setting the input value on focus
  },
  select: function (event, ui) {
    // Fires when an item is chosen
    $("#city").val(ui.item.label);
    $("#city-id").val(ui.item.value);
    return false;  // prevent default behavior
  },
  change: function (event, ui) {
    // Fires when input loses focus
    if (!ui.item) {
      // User typed something not in the list
      console.log("No match:", this.value);
    }
  },
});

범주 & 커스텀 렌더링

드롭다운 레이아웃을 커스터마이징하려 _renderMenu나 _renderItem을 오버라이드하세요. 이 예제는 헤더 행이 있는 범주별로 제안을 그룹화합니다. $.widget 패턴이 기저 autocomplete를 확장하므로 원래 옵션과 이벤트가 모두 동작합니다. 검색 인터페이스에서 흔합니다.

jquery-ui
$.widget("custom.catcomplete", $.ui.autocomplete, {
  _renderMenu: function (ul, items) {
    var that = this, currentCategory = "";
    $.each(items, function (index, item) {
      if (item.category !== currentCategory) {
        ul.append("<li class='ui-autocomplete-category'>"
          + item.category + "</li>");
        currentCategory = item.category;
      }
      that._renderItemData(ul, item);
    });
  },
});

// Use the new widget
$("#search").catcomplete({
  source: [
    { label: "Java", category: "Languages" },
    { label: "JavaScript", category: "Languages" },
    { label: "React", category: "Frameworks" },
  ],
});
09

Button

기본 Button

button 위젯이 클릭 가능한 어떤 요소(button, input[type=submit], a)든 jQuery UI 스타일로 테마합니다. ui-button 클래스를 더하고 hover/active/focus 상태를 관리합니다. 앵커가 버튼 스타일이 되어 버튼처럼 보여야 하는 내비게이션에 유용합니다.

jquery-ui
<!-- Apply to button, input, or anchor elements -->
<button id="btn">Click me</button>
<input type="submit" id="submit" value="Submit">
<a href="#" id="link" class="btn">Link button</a>

<script>
  $(function () {
    $("#btn").button();
    $("#submit").button();
    $("#link").button();
  });
</script>

Button 옵션

'icon'과 'showLabel'을 결합해 아이콘 전용 버튼(컴팩트 툴바)을 만드세요. 'iconPosition'이 아이콘이 텍스트 앞인지 뒤인지 제어합니다. 'label'로 텍스트를 프로그래밍 방식으로 설정합니다 — 런타임에 바뀔 때(예: 시작/정지 토글) 유용합니다.

jquery-ui
$("#btn").button({
  disabled: false,
  text: true,              // show the label text
  icon: "ui-icon-gear",    // primary icon class
  iconPosition: "beginning", // "beginning" or "end"
  showLabel: true,         // text or icon only
  label: "Save",           // override the button's text
});

// Icon-only button (must set showLabel: false)
$("#icon-btn").button({
  icon: "ui-icon-disk",
  showLabel: false,
});

Buttonset (라디오/체크박스 그룹)

buttonset이 라디오 버튼이나 체크박스를 시각적으로 연결된 단일 툴바로 묶습니다. jQuery UI 1.12+에서 buttonset은 더 유연하고 어떤 input 타입이든 다루는 controlgroup()으로 대체되어 폐기됐습니다. 각 input에는 대응하는 label이 필요합니다.

jquery-ui
<div id="size-set">
  <input type="radio" id="s1" name="size"><label for="s1">S</label>
  <input type="radio" id="s2" name="size" checked><label for="s2">M</label>
  <input type="radio" id="s3" name="size"><label for="s3">L</label>
</div>

<script>
  $("#size-set").buttonset();

  // For checkboxes (multi-select):
  // $("#check-set").controlgroup();  // 1.12+
</script>

아이콘

jQuery UI는 ui-icon- 접두사가 붙은 약 170개 아이콘의 스프라이트를 제공합니다. 흔한 것: ui-icon-gear, ui-icon-trash, ui-icon-search, ui-icon-close. 전체 목록은 api.jqueryui.com/theming/icons에서 보세요. 재생/일시정지식 토글은 런타임에 option 메서드로 아이콘을 바꾸세요.

jquery-ui
// Primary icon
$("#save").button({ icon: "ui-icon-disk" });

// Icon only (no text)
$("#play").button({
  icon: "ui-icon-play",
  showLabel: false,
});

// Change icon at runtime
$("#play").button("option", "icon", "ui-icon-pause");

// Available icons include:
// ui-icon-gear, ui-icon-disk, ui-icon-trash,
// ui-icon-search, ui-icon-close, ui-icon-check,
// ui-icon-arrowthick-1-n/e/s/w, and many more

분할 버튼 (툴바)

jQuery UI에는 네이티브 분할 버튼이 없습니다 — 일반 버튼과 아이콘 전용 버튼, 숨겨진 Menu를 결합해 만드세요. 화살표 버튼이 메뉴를 토글합니다. 이 패턴은 이메일 클라이언트나 문서 편집기 같은 풍부한 툴바에서 흔합니다.

jquery-ui
<div class="toolbar">
  <button id="save">Save</button>
  <button id="save-arrow"><span class="ui-icon ui-icon-triangle-1-s"></span></button>
</div>

<script>
  $("#save").button();
  $("#save-arrow").button({ text: false, icon: "ui-icon-triangle-1-s" });

  $("#save-arrow").on("click", function () {
    $("#menu").menu("widget").show();
  });
</script>

<!-- Combine with a Menu for a true split button -->
<ul id="menu" style="display:none;">
  <li><div>Save</div></li>
  <li><div>Save As...</div></li>
  <li><div>Export</div></li>
</ul>

Button 메서드

런타임에 라벨, 아이콘, disabled 상태를 바꾸려 option 메서드를 쓰세요 — '제출' → '로딩...' 같은 상태 있는 버튼의 전형입니다. refresh 메서드가 요소 상태를 다시 읽습니다(프로그래밍 방식으로 토글된 체크박스에 유용). destroy가 모든 스타일링을 제거합니다.

jquery-ui
// Disable / enable
$("#btn").button("disable");
$("#btn").button("enable");

// Change options
$("#btn").button("option", "label", "Loading...");
$("#btn").button("option", "disabled", true);

// Get the button element
$("#btn").button("widget");

// Refresh after DOM changes (e.g. removing a class)
$("#btn").button("refresh");

// Remove the widget
$("#btn").button("destroy");
10

Datepicker

기본 Datepicker

input을 클릭하거나 포커스하면 캘린더 팝업이 열립니다. 선택된 날짜가 텍스트로 input을 채웁니다. 캘린더가 이전/다음 달 내비게이션 화살표와 함께 현재 달을 보여줍니다. 기본 날짜 형식은 미국식(mm/dd/yy)입니다.

jquery-ui
<label for="date">Pick a date:</label>
<input type="text" id="date">

<script>
  $(function () {
    $("#date").datepicker();
  });
</script>

Datepicker 옵션

minDate/maxDate는 Date 객체, 숫자(오늘부터 며칠), 문자열('+1M +1W')을 받습니다. numberOfMonths가 여러 달을 표시합니다 — 날짜 범위 피커에 유용. changeMonth/changeYear가 먼 연도로 점프하는 드롭다운을 추가합니다.

jquery-ui
$("#date").datepicker({
  dateFormat: "yy-mm-dd",     // ISO format
  defaultDate: "+1",          // tomorrow when calendar opens
  minDate: 0,                 // no past dates (today+)
  maxDate: "+1Y",             // up to one year ahead
  numberOfMonths: 2,          // show 2 months side by side
  showButtonPanel: true,      // Today/Done buttons
  changeMonth: true,          // dropdown for month
  changeYear: true,           // dropdown for year
  showAnim: "fadeIn",         // open animation
  duration: "fast",
  firstDay: 1,                // start week on Monday
  showWeek: true,             // show week numbers
});

날짜 형식

dateFormat 옵션은 PHP식 토큰을 씁니다. 'yy'는 네 자리 연도입니다(추가 y는 의도적). formatDate() 메서드로 같은 토큰으로 Date를 문자열로 바꾸고, parseDate()로 되돌리세요.

jquery-ui
$("#date").datepicker({
  dateFormat: "yy-mm-dd",  // 2026-07-04
});

// Format tokens:
// d  - day of month, no leading zero (1)
// dd - day, two digits (01)
// D  - short day name (Mon)
// DD - full day name (Monday)
// m  - month, no leading zero (1)
// mm - month, two digits (01)
// M  - short month name (Jan)
// MM - full month name (January)
// y  - two-digit year (26)
// yy - four-digit year (2026)
// @  - Unix timestamp
// ! - Windows ticks

// Common formats:
// "mm/dd/yy"      -> 07/04/2026
// "yy-mm-dd"      -> 2026-07-04
// "DD, MM d, yy"  -> Friday, July 4, 2026

최소/최대 날짜 & 범위

날짜 범위 피커는 두 데이트피커를 연결합니다: 시작이 선택되면 끝의 minDate를 설정하고, 끝이 선택되면 시작의 maxDate를 설정합니다. beforeShowDay로 개별 날짜를 비활성화하거나 스타일링할 수 있습니다 — noWeekends가 토요일과 일요일을 막는 내장입니다.

jquery-ui
// Restrict to a date range
$("#start").datepicker({
  minDate: 0,
  maxDate: "+6M",
  onSelect: function (dateText) {
    // Set the end date's minimum to the start date
    $("#end").datepicker("option", "minDate", dateText);
  },
});
$("#end").datepicker({
  minDate: 0,
  maxDate: "+6M",
  onSelect: function (dateText) {
    $("#start").datepicker("option", "maxDate", dateText);
  },
});

// Disable weekends
$("#date").datepicker({
  beforeShowDay: $.datepicker.noWeekends,
});

지역화

jQuery UI는 i18n 폴더에 약 40개 로케일의 지역 파일을 제공합니다. 파일을 로드하고 $.datepicker.regional['fr']로 적용하세요. 개별 문자열을 인라인으로 오버라이드할 수도 있습니다. 지역 파일이 달 이름, 요일 이름, firstDay, dateFormat을 한 번에 설정합니다.

jquery-ui
// Set the regionalization
$("#date").datepicker($.datepicker.regional["fr"]);

// Override specific strings
$("#date").datepicker({
  monthNames: ["janvier","février","mars","avril","mai","juin",
               "juillet","août","septembre","octobre","novembre","décembre"],
  dayNamesMin: ["Di","Lu","Ma","Me","Je","Ve","Sa"],
  firstDay: 1,
  dateFormat: "dd/mm/yy",
  prevText: "Précédent",
  nextText: "Suivant",
  closeText: "Fermer",
  currentText: "Aujourd'hui",
});

// Include the regional file for built-in locales:
// <script src="jquery-ui/i18n/datepicker-fr.js"></script>

인라인 Datepicker & 이벤트

input 대신 div에 datepicker를 적용하면 항상 보이는 인라인 캘린더가 됩니다 — 예약 인터페이스에 좋습니다. onSelect는 날짜가 선택될 때, onChangeMonthYear는 달을 이동할 때 발생합니다. getDate/setDate가 프로그래밍 제어용 Date 객체로 동작합니다.

jquery-ui
<!-- Inline (always visible) calendar -->
<div id="inline-calendar"></div>

<script>
  $("#inline-calendar").datepicker({
    onSelect: function (dateText, inst) {
      console.log("Selected:", dateText);
    },
    onChangeMonthYear: function (year, month, inst) {
      console.log("Viewing:", month + "/" + year);
    },
    beforeShow: function (input, inst) {
      // Fires before the popup opens
      return { /* override options */ };
    },
    onClose: function (dateText, inst) {
      // Fires when the popup closes
    },
  });

  // Methods
  $("#date").datepicker("setDate", "+7");  // set to a week from today
  $("#date").datepicker("getDate");        // returns a Date object
  $("#date").datepicker("option", "minDate", new Date(2026, 0, 1));
</script>
11

Dialog

기본 Dialog

요소의 title 속성이 다이얼로그 제목 표시줄이 됩니다. 다이얼로그는 기본 자동 열림이며 드래그/리사이즈 가능합니다. 요소가 올바른 z-index 쌓임을 갖는 jQuery UI 래퍼로 이동합니다. X 버튼이나 Escape로 닫습니다.

jquery-ui
<div id="dialog" title="Basic dialog">
  <p>This is a simple dialog window.</p>
</div>

<script>
  $(function () {
    $("#dialog").dialog();
  });
</script>

Dialog 옵션

숨겨진 다이얼로그를 만들려 autoOpen: false를 설정하고 필요할 때 dialog('open')을 호출하세요 — 온디맨드 다이얼로그의 표준 패턴입니다. modal이 페이지 상호작용을 막는 오버레이를 더합니다. position이 정밀 배치에 jQuery UI Position 유틸리티를 씁니다.

jquery-ui
$("#dialog").dialog({
  autoOpen: false,           // don't open on init
  modal: true,               // dim the page behind
  width: 400,
  height: "auto",
  minWidth: 200,
  maxWidth: 600,
  resizable: true,
  draggable: true,
  closeOnEscape: true,
  position: { my: "center", at: "center", of: window },
  title: "Custom Title",     // override the title attr
  show: { effect: "fade", duration: 200 },
  hide: { effect: "fade", duration: 200 },
});

Dialog 버튼

buttons는 배열(권장, 아이콘과 버튼별 옵션 허용)이나 객체(text: 핸들러)를 받습니다. 핸들러 안에서 'this'는 다이얼로그 요소입니다 — 닫으려 $(this).dialog('close')를 호출하세요. 버튼은 자동 테마되며 기본 오른쪽 정렬입니다.

jquery-ui
$("#dialog").dialog({
  buttons: [
    {
      text: "Save",
      icon: "ui-icon-disk",
      click: function () {
        saveForm();
        $(this).dialog("close");
      },
    },
    {
      text: "Cancel",
      click: function () {
        $(this).dialog("close");
      },
    },
  ],
});

// Shortcut object form (1.12+)
$("#dialog").dialog({
  buttons: {
    "Save": function () { saveForm(); $(this).dialog("close"); },
    "Cancel": function () { $(this).dialog("close"); },
  },
});

Dialog 이벤트

beforeClose가 문지기입니다 — false를 반환하면 다이얼로그가 열려 유지됩니다(저장되지 않은 변경 경고에 유용). close는 다이얼로그가 닫힌 뒤 발생하며 폼 상태 리셋이나 리소스 해제의 적합한 자리입니다. drag/resize 이벤트가 기저 인터랙션의 것을 미러링합니다.

jquery-ui
$("#dialog").dialog({
  beforeClose: function (event, ui) {
    // Return false to prevent closing
    if (!confirm("Discard changes?")) return false;
  },
  open: function (event, ui) {
    console.log("Dialog opened");
  },
  close: function (event, ui) {
    console.log("Dialog closed");
    // Clean up form state
    $(this).find("form")[0].reset();
  },
  focus: function (event, ui) {
    // Dialog gained focus
  },
  dragStart: function (event, ui) { /* dragging started */ },
  dragStop: function (event, ui) { /* dragging ended */ },
  resizeStart: function (event, ui) { /* resizing started */ },
  resizeStop: function (event, ui) { /* resizing ended */ },
});

모달 & 확인 다이얼로그

일회성 확인을 위해 동적으로 만든 요소로 다이얼로그를 만드세요. 모달 오버레이가 페이지 나머지와의 상호작용을 막습니다. 다이얼로그가 닫힐 때 DOM 노드가 새지 않도록 close 핸들러에서 항상 destroy하고 요소를 제거하세요.

jquery-ui
function confirmDialog(message, onConfirm) {
  $("<div>" + message + "</div>").dialog({
    modal: true,
    title: "Confirm",
    buttons: {
      "OK": function () {
        onConfirm();
        $(this).dialog("close");
      },
      "Cancel": function () {
        $(this).dialog("close");
      },
    },
    close: function () {
      $(this).dialog("destroy").remove();  // clean up
    },
  });
}

// Usage
confirmDialog("Delete this item?", function () {
  deleteItem();
});

AJAX 콘텐츠 & 메서드

open 이벤트로 AJAX로 콘텐츠를 로드하고 중첩 위젯을 초기화하세요. 다음 열림이 새것이도록 닫을 때 항상 콘텐츠를 비우세요. moveToTop이 z-index에서 다른 것들 위로 다이얼로그를 올립니다 — 쌓인 다이얼로그에 유용. isOpen이 조건 로직용 불리언 게터입니다.

jquery-ui
// Load content from a URL when opening
function openEditDialog(id) {
  var $dlg = $("#edit-dialog");
  $dlg.dialog({
    autoOpen: false,
    modal: true,
    open: function () {
      $dlg.load("/api/edit/" + id, function () {
        // Initialize widgets in loaded content
        $dlg.find(".datepicker").datepicker();
      });
    },
    close: function () {
      $dlg.empty();  // clear for next open
    },
  });
  $dlg.dialog("open");
}

// Common methods
$("#dialog").dialog("open");
$("#dialog").dialog("close");
$("#dialog").dialog("isOpen");   // returns boolean
$("#dialog").dialog("moveToTop"); // bring to front
$("#dialog").dialog("option", "title", "New Title");
13

Progressbar

기본 Progressbar

progressbar가 백분율(0-100)까지 채워진 가로 막대를 보여줍니다. value 옵션이 현재 진행을 정합니다. 막대가 jQuery UI 스타일로 자동 테마됩니다. 컨테이너 너비가 전체 막대 너비를 결정합니다 — CSS로 설정하세요.

jquery-ui
<div id="progress"></div>

<script>
  $(function () {
    $("#progress").progressbar({ value: 37 });
  });
</script>

미정 모드

value를 false로 두면 막대가 미정 모드가 됩니다 — 애니메이션 스트라이프가 특정 백분율 없이 '무언가 진행 중'을 나타냅니다. 총량을 모를 때(예: 서버 대기) 쓰세요. 진행을 추적할 수 있게 되면 다시 숫자로 전환하세요.

jquery-ui
<div id="progress"></div>

<script>
  // Set value to false for an indeterminate (animated) bar
  $("#progress").progressbar({ value: false });

  // Switch to determinate later when you know the percent
  $("#progress").progressbar("option", "value", 50);
</script>

Progressbar 옵션

'max' 옵션으로 100이 아닌 스케일을 쓸 수 있습니다(예: KB 단위 다운로드에는 max: 1000). 값이 max의 비율로 해석됩니다. classes 옵션(1.12+)이 세밀한 테마를 위해 특정 내부 요소에 커스텀 클래스를 추가하게 합니다.

jquery-ui
$("#progress").progressbar({
  value: 0,           // 0-100, or false for indeterminate
  max: 100,           // upper bound (default 100)
  disabled: false,
  // 1.12+ supports a 'classes' option for theming
  classes: {
    "ui-progressbar": "highlight",
    "ui-progressbar-value": "animated",
  },
});

값 갱신

value 옵션을 설정해 막대를 갱신하세요. setInterval 루프가 업로드나 오래 걸리는 작업의 진행을 흉내 냅니다. 실제 업로드에는 XHR 업로드 진행 이벤트로 전송된 바이트 기반 value를 갱신하세요. 끝나면 항상 타이머를 지우세요.

jquery-ui
// Simulate a file upload
var progress = 0;
$("#progress").progressbar({ value: 0 });

var timer = setInterval(function () {
  progress += 5;
  $("#progress").progressbar("option", "value", progress);
  if (progress >= 100) {
    clearInterval(timer);
    console.log("Complete!");
  }
}, 200);

// Get current value
var current = $("#progress").progressbar("option", "value");

change 이벤트 & 커스텀 라벨

change는 값이 갱신될 때마다, complete는 100%에서 발생합니다 — 둘 다 동적 스타일링이나 라벨에 유용합니다. 백분율 텍스트를 보여주려 막대 위에 절대 위치 라벨을 추가하세요. 동기화를 위해 change 핸들러 안에서 갱신하세요.

jquery-ui
$("#progress").progressbar({
  value: 0,
  change: function () {
    var v = $("#progress").progressbar("value");
    $("#progress .ui-progressbar-value")
      .css("background", v < 50 ? "#fa0" : "#0a0");
  },
  complete: function () {
    $("#progress .ui-progressbar-value").css("background", "#0a0");
    $("#progress-label").text("Done!");
  },
});

// Overlay a text label
$("#progress").append(
  '<div id="progress-label" style="position:absolute;left:50%;top:0;">Loading...</div>'
);
14

Selectmenu

기본 Selectmenu

selectmenu가 네이티브 select 드롭다운을 jQuery UI 테마 버전으로 교체합니다. 모든 네이티브 기능(선택됨, 비활성 옵션)을 지원하고 아이콘, 커스텀 렌더링, 일관된 크로스 브라우저 스타일을 더합니다. 기저 select가 동기화되므로 폼이 정상 제출됩니다.

jquery-ui
<label for="speed">Speed:</label>
<select id="speed">
  <option>Slower</option>
  <option>Slow</option>
  <option selected="selected">Medium</option>
  <option>Fast</option>
  <option>Faster</option>
</select>

<script>
  $(function () {
    $("#speed").selectmenu();
  });
</script>

Selectmenu 옵션

width를 null로 두면 요소의 CSS 너비를, 숫자를 두면 명시적 픽셀을 씁니다. 기본 너비가 가장 긴 옵션에 맞춰 자동 조정됩니다. position이 버튼 기준 메뉴 배치를 제어합니다. 다이얼로그나 iframe 안의 selectmenu에는 appendTo가 유용합니다.

jquery-ui
$("#speed").selectmenu({
  disabled: false,
  width: null,            // null = CSS width, number = px
  icons: { button: "ui-icon-triangle-1-s" },
  appendTo: null,         // where to render the menu
  position: { my: "left top", at: "left bottom" },
});

Selectmenu 이벤트

change가 주 이벤트입니다 — 사용자가 다른 옵션을 고를 때 발생합니다. ui.item.value가 옵션의 value 속성이고, ui.item.label이 텍스트입니다. select는 change 직전에 발생하며 false를 반환해 취소할 수 있습니다 — 검증에 유용합니다.

jquery-ui
$("#speed").selectmenu({
  change: function (event, ui) {
    // ui.item has the selected option's data
    console.log("Selected:", ui.item.value);
    console.log("Label:", ui.item.label);
  },
  focus: function (event, ui) {
    // Item highlighted in the dropdown
  },
  open: function (event, ui) {
    // Dropdown just opened
  },
  close: function (event, ui) {
    // Dropdown just closed
  },
  select: function (event, ui) {
    // Fires before change; return false to cancel
  },
});

커스텀 렌더링

각 옵션에 아이콘, 설명, 커스텀 HTML을 더하려 _renderItem을 오버라이드하세요. item.element가 원래 <option>에 접근하게 해 데이터 속성을 읽을 수 있습니다. 상태 아이콘이 있는 프로젝트 선택기 같은 풍부한 드롭다운의 표준 방법입니다.

jquery-ui
$("#projects").selectmenu({
  // Render each item in the dropdown
  format: function (item) {
    // (deprecated in 1.12 — use _renderItem instead)
  },
});

// 1.12+ custom rendering via widget extension
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
  _renderItem: function (ul, item) {
    var li = $("<li>"), wrapper = $("<div>", { text: item.label });
    if (item.disabled) li.addClass("ui-state-disabled");
    $("<span>", { class: "ui-icon " + item.element.data("icon") })
      .appendTo(wrapper);
    return li.append(wrapper).appendTo(ul);
  },
});

$("#projects").iconselectmenu();

메서드

값을 설정하려 select의 네이티브 .val()을 쓴 뒤 refresh()를 호출해 위젯 표시를 갱신하세요. 기저 select에서 옵션을 추가, 제거, 변경한 뒤에는 항상 refresh()를 호출해 위젯이 새 상태를 반영하게 하세요.

jquery-ui
// Open / close programmatically
$("#speed").selectmenu("open");
$("#speed").selectmenu("close");

// Get or set the value
var val = $("#speed").selectmenu("option", "value");  // not standard
$("#speed").val("fast").selectmenu("refresh");  // use .val() + refresh

// Refresh after modifying the underlying select
$("#speed").append("<option>New</option>");
$("#speed").selectmenu("refresh");

// Disable / enable
$("#speed").selectmenu("disable");
$("#speed").selectmenu("enable");

// Get the button or menu element
$("#speed").selectmenu("widget");    // the button wrapper
$("#speed").selectmenu("menuWidget"); // the menu ul

// Destroy
$("#speed").selectmenu("destroy");

Optgroup & 비활성 옵션

selectmenu는 네이티브 <optgroup> 요소를 존중합니다 — 적절한 테마와 함께 선택 불가능한 그룹 헤더로 렌더링됩니다. 개별 옵션의 disabled 속성도 존중되어 회색으로 표시되고 선택이 막힙니다. 폼은 여전히 선택된 값을 제출합니다.

jquery-ui
<select id="category">
  <optgroup label="Frontend">
    <option value="react">React</option>
    <option value="vue">Vue</option>
  </optgroup>
  <optgroup label="Backend">
    <option value="node">Node.js</option>
    <option value="django" disabled>Django (deprecated)</option>
  </optgroup>
</select>

<script>
  $("#category").selectmenu({
    width: 200,
    change: function (event, ui) {
      console.log("Picked:", ui.item.value);
    },
  });
</script>
15

Slider

기본 Slider

slider가 가로 트랙에 드래그 가능한 핸들을 만듭니다. 기본 범위는 0-100이며 핸들이 0에서 시작합니다. 트랙이 완전히 테마됩니다. 치수는 컨테이너의 CSS로 설정하세요 — 가로 슬라이더에는 width, 세로에는 height.

jquery-ui
<div id="slider"></div>

<script>
  $(function () {
    $("#slider").slider();
  });
</script>

Slider 옵션

이중 핸들 범위 슬라이더에는 'value' 대신 'values'(배열)를 쓰세요. 'range: true'가 핸들 사이 영역을 음영 처리하고, 'range: min'은 핸들에서 최소까지, 'range: max'는 핸들에서 최대까지입니다. 'step'은 (max - min)을 나눠 떨어져야 합니다.

jquery-ui
$("#slider").slider({
  min: 0,
  max: 100,
  step: 1,                  // increment size
  value: 50,                // single value
  values: [25, 75],         // two-handle range (omit 'value')
  orientation: "horizontal", // or "vertical"
  range: true,              // or "min", "max"
  disabled: false,
  animate: "fast",          // or ms, or false
});

Slider 이벤트

slide는 드래그 중 계속 발생합니다 — 라벨 실시간 갱신에 이상적입니다. slide 안에서 false를 반환하면 이동이 취소되어 값 동적 제한에 유용합니다. change는 놓은 뒤와 프로그래밍 방식 옵션 변경에 발생합니다 — 값 영속화에 쓰세요.

jquery-ui
$("#slider").slider({
  start: function (event, ui) {
    // User started dragging a handle
    console.log("Start:", ui.value || ui.values);
  },
  slide: function (event, ui) {
    // Fires continuously during drag
    // Return false to prevent the handle from moving
    $("#label").text(ui.value);
  },
  change: function (event, ui) {
    // Fires after the handle is released (and on programmatic change)
    saveValue(ui.value);
  },
  stop: function (event, ui) {
    // User released the handle
  },
});

범위 슬라이더

이중 핸들 범위 슬라이더는 range: true와 values 배열로 만듭니다. ui.values[0]가 낮은 핸들이고, ui.values[1]가 높은 핸들입니다. 핸들은 교차할 수 없습니다. 가격이나 날짜 범위 필터의 클래식 패턴입니다.

jquery-ui
<div id="range-slider"></div>
<p>Price: $<span id="min-price"></span> - $<span id="max-price"></span></p>

<script>
  $("#range-slider").slider({
    range: true,
    min: 0,
    max: 500,
    values: [75, 300],
    slide: function (event, ui) {
      $("#min-price").text(ui.values[0]);
      $("#max-price").text(ui.values[1]);
    },
  });
</script>

세로 & 방향

세로 슬라이더에는 CSS로 명시적 높이가 필요합니다 — width가 교차축에 적용됩니다. 핸들이 좌우 대신 위/아래로 움직입니다. 범위 음영도 같은 방식으로 동작합니다. 오디오 믹서, 이퀄라이저, 세로 방향이 더 자연스러운 UI에 유용합니다.

jquery-ui
// Vertical slider
$("#vertical").slider({
  orientation: "vertical",
  min: 0,
  max: 100,
  value: 60,
});

// Vertical range
$("#vertical-range").slider({
  orientation: "vertical",
  range: true,
  min: 0,
  max: 100,
  values: [20, 80],
});

/* CSS: vertical sliders need a height */
/* #vertical { height: 200px; } */
</script>

Slider 메서드

범위 슬라이더에는 배열 얻기에 values()(인수 없음), 한 핸들 설정에 values(index, value), 둘 다 설정에 values(array)를 쓰세요. 런타임에 min/max/step 같은 옵션을 설정하면 핸들이 새 경계 안에서 자동 재배치됩니다.

jquery-ui
// Get or set the value
$("#slider").slider("value");
$("#slider").slider("value", 75);

// Get or set both handles of a range slider
var vals = $("#slider").slider("values");  // [25, 75]
$("#slider").slider("values", 0, 30);      // set lower handle
$("#slider").slider("values", [30, 90]);   // set both

// Get or set options
$("#slider").slider("option", "max", 200);
$("#slider").slider("option", "disabled", true);

// Disable / enable / destroy
$("#slider").slider("disable");
$("#slider").slider("enable");
$("#slider").slider("destroy");
16

Spinner

기본 Spinner

spinner가 숫자 입력용 텍스트 input에 위/아래 버튼을 더합니다. 사용자는 직접 타이핑하거나, 버튼을 클릭하거나, 화살표 키를 쓸 수 있습니다. 버튼을 누르고 있으면 증분이 가속됩니다. input 값은 변경마다 숫자로 파싱됩니다.

jquery-ui
<label for="qty">Quantity:</label>
<input id="qty" type="text" value="1">

<script>
  $(function () {
    $("#qty").spinner();
  });
</script>

Spinner 옵션

min/max가 경계를 강제합니다 — 버튼이 이를 넘지 않습니다. step이 증분 크기를 제어합니다(세밀한 제어에는 0.1 같은 소수). culture가 있는 numberFormat이 지역화된 형식을 가능하게 합니다(예: 'ja-JP'와 함께 'C'는 엔 표시). culture 지원에는 Globalize.js가 로드되어야 합니다.

jquery-ui
$("#qty").spinner({
  min: 0,                   // minimum value
  max: 100,                 // maximum value
  step: 1,                  // increment size
  page: 10,                 // page up/down increment
  numberFormat: "n",        // "n" for number, "C" for currency
  culture: "en-US",         // locale for formatting
  disabled: false,
  incremental: true,        // accelerate while holding
  icons: {
    up: "ui-icon-triangle-1-n",
    down: "ui-icon-triangle-1-s",
  },
});

숫자 형식 & Culture

Globalize.js가 로드되면 spinner가 지정된 culture 기준으로 값을 형식합니다 — 통화 기호, 소수 구분자, 자릿수 묶음이 모두 지역화됩니다. numberFormat 'C'는 통화, 'n'은 선택적 소수 자릿수가 있는 숫자입니다(n2 = 소수 2자리). 국제화된 폼에 유용합니다.

jquery-ui
<!-- Requires Globalize.js for culture support -->
<script src="globalize.js"></script>
<script src="globalize.culture.ja-JP.js"></script>

<script>
  // Currency spinner (Japanese yen)
  $("#price").spinner({
    numberFormat: "C",
    culture: "ja-JP",
    step: 100,
    min: 0,
  });

  // Decimal spinner
  $("#weight").spinner({
    step: 0.01,
    numberFormat: "n2",  // 2 decimal places
    min: 0,
  });
</script>

Spinner 이벤트

spin은 증가/감소마다(버튼 클릭이나 화살표 키) 발생합니다. false를 반환하면 변화가 취소됩니다 — 커스텀 검증에 이상적입니다. change는 blur에서 발생하며, input이 유효한 숫자로 파싱되지 않으면 ui.value가 null입니다 — 검증 오류를 보여줄 자리입니다.

jquery-ui
$("#qty").spinner({
  spin: function (event, ui) {
    // Fires when a button is clicked or arrow pressed
    // ui.value is the new value
    // Return false to cancel the change
    if (ui.value > 10) {
      alert("Max 10 per order");
      return false;
    }
  },
  change: function (event, ui) {
    // Fires when the value changes and input loses focus
    // ui.value may be null if invalid
    if (ui.value === null) {
      alert("Please enter a valid number");
    }
  },
  start: function (event, ui) { /* spin started */ },
  stop: function (event, ui) { /* spin stopped */ },
});

커스텀 step & 메서드

stepUp/stepDown/pageUp/pageDown이 프로그래밍 방식 버튼 누름을 흉내 냅니다. 인수 없는 value()가 게터이고, 인수와 함께면 검증을 거치는 세터입니다. 커스텀 spin 핸들러로 시간, 색, 커스텀 단위 같은 비숫자 스피너를 만들 수 있습니다.

jquery-ui
// Time spinner (steps of 15 minutes)
$("#time").spinner({
  step: 15,
  min: 0,
  max: 1439,  // 24 * 60 - 1
  numberFormat: "n0",
  spin: function (event, ui) {
    // Wrap around at midnight
    if (ui.value > 1439) return false;  // or wrap: $(this).spinner("value", 0);
  },
});

// Methods
$("#qty").spinner("value");        // get current value
$("#qty").spinner("value", 5);     // set value
$("#qty").spinner("stepUp");       // increment by one step
$("#qty").spinner("stepDown");     // decrement by one step
$("#qty").spinner("pageUp");       // increment by 'page' steps
$("#qty").spinner("pageDown");
$("#qty").spinner("disable");
$("#qty").spinner("enable");
$("#qty").spinner("destroy");

검증 & 커스텀 파싱

비십진 값용 스피너를 만들려 _parse와 _format을 오버라이드하세요 — 16진수 색, 시간, 각도, 임의의 커스텀 단위. _parse가 input 텍스트를 숫자로 바꾸고, _format이 표시용으로 되돌립니다. 도메인별 input용으로 spinner를 확장하는 가장 깔끔한 방법입니다.

jquery-ui
// Custom spinner for hexadecimal colors
$.widget("custom.hexspinner", $.ui.spinner, {
  _parse: function (value) {
    // String -> number
    return parseInt(value, 16);
  },
  _format: function (value) {
    // number -> string
    return value.toString(16).toUpperCase().padStart(6, "0");
  },
});

$("#color").hexspinner({
  min: 0x000000,
  max: 0xffffff,
  step: 0x10,
});

// Prevent invalid input
$("#qty").on("keydown", function (e) {
  if (e.key === "-" && $(this).spinner("option", "min") >= 0) {
    e.preventDefault();
  }
});
17

Tabs

기본 Tabs

tabs는 콘텐츠 패널 ID를 가리키는 링크의 ul과 그 뒤의 패널들을 기대합니다. 링크 href(#tab-1)가 탭을 패널에 연결합니다. 첫 탭이 기본 활성입니다. 탭은 키보드 내비게이션(화살표, Home, End)이 되고 ARIA 준수입니다.

jquery-ui
<div id="tabs">
  <ul>
    <li><a href="#tab-1">First</a></li>
    <li><a href="#tab-2">Second</a></li>
    <li><a href="#tab-3">Third</a></li>
  </ul>
  <div id="tab-1">Content 1</div>
  <div id="tab-2">Content 2</div>
  <div id="tab-3">Content 3</div>
</div>

<script>
  $(function () {
    $("#tabs").tabs();
  });
</script>

Tabs 옵션

active가 인덱스로 처음 열릴 탭을 정합니다(접힌 채 시작하려 false). heightStyle 'fill'은 모든 패널을 컨테이너 높이로 만들고, 'content'는 각자 콘텐츠 크기로 맞춥니다(기본값). 'event: mouseover'가 hover 활성 탭을 만듭니다.

jquery-ui
$("#tabs").tabs({
  active: 0,            // index of active tab (false = all hidden)
  collapsible: false,   // allow closing the active tab
  disabled: [],         // array of disabled indices
  event: "click",       // event to switch tabs ("mouseover" etc.)
  heightStyle: "content", // "auto", "fill", or "content"
  show: { effect: "fadeIn", duration: 200 },
  hide: { effect: "fadeOut", duration: 200 },
});

Tabs 이벤트

beforeActivate가 문지기입니다 — 전환을 막으려 false를 반환하세요(예: 저장되지 않은 변경 경고). activate는 전환 완료 후 발생합니다. beforeLoad/load는 AJAX 탭용입니다 — beforeLoad로 요청을 커스터마이징하거나 취소할 수 있고, load는 성공 시 발생합니다.

jquery-ui
$("#tabs").tabs({
  beforeActivate: function (event, ui) {
    // ui.newTab, ui.newPanel (opening)
    // ui.oldTab, ui.oldPanel (closing)
    // Return false to cancel the switch
    if ($(ui.newPanel).find("form").hasUnsavedChanges()) {
      return confirm("Discard changes?");
    }
  },
  activate: function (event, ui) {
    // Fires after the new tab is shown
    console.log("Now on:", ui.newTab.text());
  },
  beforeLoad: function (event, ui) {
    // For AJAX tabs — fires before loading remote content
    ui.jqXHR.error(function () {
      ui.panel.text("Failed to load content.");
    });
  },
  load: function (event, ui) {
    // AJAX content finished loading
  },
});

AJAX 탭

탭의 href가 URL(앵커 아님)이면 tabs가 활성화 시 콘텐츠를 AJAX로 로드합니다. 응답이 패널을 교체합니다. beforeLoad로 스피너 표시, AJAX 요청 설정, 취소가 가능합니다. 로드된 콘텐츠는 1.12+에서 기본적으로 세션 동안 캐시됩니다.

jquery-ui
<div id="tabs">
  <ul>
    <li><a href="#local">Local</a></li>
    <li><a href="remote.html">Remote (AJAX)</a></li>
    <li><a href="api/data.json">API Data</a></li>
  </ul>
  <div id="local">This content is in the page.</div>
  <!-- Remote panels are created automatically -->
</div>

<script>
  $("#tabs").tabs({
    beforeLoad: function (event, ui) {
      // Show a loading indicator
      ui.panel.html("Loading...");
      // Cache the loaded content
      ui.ajaxSettings.cache = true;
    },
  });
</script>

collapsible & sortable 탭

collapsible: true이면 활성 탭을 클릭하면 닫힙니다(열려 있는 탭이 없어짐). nav의 sortable과 탭을 짝지으면 사용자가 드래그로 탭을 재정렬합니다. 탭/패널을 추가하거나 제거한 뒤 refresh()를 호출해 위젯이 새 구조를 재바인딩하게 하세요.

jquery-ui
// Allow collapsing the active tab
$("#tabs").tabs({ collapsible: true });

// Make tabs reorderable by drag
$("#tabs").tabs().find(".ui-tabs-nav").sortable({
  axis: "x",
  stop: function () {
    $("#tabs").tabs("refresh");
  },
});

// Dynamically add a new tab
function addTab(id, label, content) {
  var nav = $("#tabs .ui-tabs-nav");
  nav.append('<li><a href="#' + id + '">' + label + '</a></li>');
  $("#tabs").append('<div id="' + id + '">' + content + '</div>');
  $("#tabs").tabs("refresh");
}

Tabs 메서드

disable/enable은 인덱스나 인덱스 배열을 받습니다. active 옵션이 현재 탭의 게터이자 세터입니다 — 프로그래밍 방식 전환에 쓰세요. load()가 탭의 AJAX 콘텐츠를 다시 로드합니다. refresh()는 탭을 추가, 제거, 재정렬한 뒤 필수입니다.

jquery-ui
// Disable / enable specific tabs
$("#tabs").tabs("disable", 1);       // disable second tab
$("#tabs").tabs("enable", 1);
$("#tabs").tabs("option", "disabled", [0, 2]);  // disable multiple

// Switch to a tab by index
$("#tabs").tabs("option", "active", 2);

// Reload an AJAX tab
$("#tabs").tabs("load", 1);

// Refresh after structural changes
$("#tabs").tabs("refresh");

// Get the active tab index
var active = $("#tabs").tabs("option", "active");

// Destroy
$("#tabs").tabs("destroy");
18

Tooltip

기본 Tooltip

document에 tooltip()을 호출하면 모든 네이티브 title 툴팁이 테마된 jQuery UI 버전으로 교체됩니다. title 속성의 콘텐츠가 툴팁 텍스트가 됩니다. 툴팁은 hover에 나타나고 mouseout에서 사라지며 기본 부드러운 페이드 애니메이션을 씁니다.

jquery-ui
<label for="age">Age:</label>
<input id="age" title="Please enter your age in years">

<script>
  $(function () {
    $(document).tooltip();
  });
</script>

Tooltip 옵션

'content'를 함수로 오버라이드하면 동적 툴팁 HTML(데이터 속성이나 AJAX에서)을 생성합니다. 'items'가 어떤 요소가 툴팁을 트리거하는지 제어하는 선택자입니다. 'track: true'는 툴팁이 커서를 따르게 합니다 — 다이어그램의 상세 도움말 텍스트에 유용합니다.

jquery-ui
$(document).tooltip({
  content: function () {
    // Default: returns the element's title attribute
    return $(this).attr("title");
  },
  items: "[title]",       // which elements get tooltips
  position: { my: "left top+15", at: "left bottom" },
  show: { effect: "fadeIn", duration: 200 },
  hide: { effect: "fadeOut", duration: 200 },
  tooltipClass: "custom-tooltip",  // class for the tooltip div
  track: false,           // follow the mouse cursor
  disabled: false,
  close: null,            // (event defaults handle this)
});

커스텀 콘텐츠

content 함수로 HTML, 이미지, AJAX로 가져온 콘텐츠의 풍부한 툴팁을 만들 수 있습니다. 문자열을 반환하세요(HTML 허용). tooltipClass가 스타일링용 커스텀 클래스를 추가합니다. 썸네일 미리보기나 폼 필드의 도움말 버블의 표준 패턴입니다.

jquery-ui
<!-- HTML with data attributes -->
<a href="#" class="help" data-help="Click to save your changes">Save</a>
<a href="#" class="help" data-help="Undo the last action">Undo</a>

<script>
  $(".help").tooltip({
    content: function () {
      return "<strong>Help:</strong> " + $(this).data("help");
    },
    tooltipClass: "help-tooltip",
  });
</script>

<!-- With an image preview -->
$(".thumb").tooltip({
  content: function () {
    var src = $(this).attr("href");
    return "<img src='" + src + "' width='200'>";
  },
});

Tooltip 이벤트

open과 close가 툴팁이 나타나고 사라질 때 발생합니다. ui.tooltip 프로퍼티가 커스터마이징용 툴팁 요소를 줍니다. 흔한 패턴은 사용자가 툴팁 위에 있는 동안 열어 두는 것입니다 — 툴팁이 링크 같은 인터랙티브 콘텐츠를 담을 때 유용합니다.

jquery-ui
$(".help").tooltip({
  open: function (event, ui) {
    // Tooltip just appeared
    ui.tooltip;  // the tooltip element
  },
  close: function (event, ui) {
    // Tooltip just disappeared
    ui.tooltip.one("transitionend", function () {
      // Cleanup after the hide animation
    });
  },
  create: function (event, ui) {
    // Widget initialized
  },
});

// Prevent tooltip from closing on hover
$(".help").tooltip({
  close: function (event, ui) {
    ui.tooltip.hover(
      function () { $(this).stop(true).fadeIn(); },
      function () { $(this).fadeOut(); }
    );
  },
});

position & 메서드

position은 jQuery UI Position 유틸리티를 씁니다: 'my'가 툴팁의 앵커이고, 'at'이 대상의 앵커입니다. collision이 가장자리 사례를 처리합니다 — 'flip'은 넘치면 반대편으로 이동합니다. open()/close()가 프로그래밍 방식 툴팁 표시/숨김입니다 — 검증 오류에 유용합니다.

jquery-ui
$("#target").tooltip({
  position: {
    my: "center top",       // tooltip's anchor point
    at: "center bottom",    // target's anchor point
    of: "#target",          // optional: position relative to this
    collision: "flip",      // "flip", "fit", "flipfit", "none"
    using: function (pos, feedback) {
      $(this).css(pos);
      console.log(feedback.horizontal, feedback.vertical);
    },
  },
});

// Methods
$("#target").tooltip("open");   // show programmatically
$("#target").tooltip("close");  // hide programmatically
$("#target").tooltip("disable");
$("#target").tooltip("enable");
$("#target").tooltip("widget");  // get the tooltip div
$("#target").tooltip("destroy");

폼 검증 툴팁

툴팁은 인라인 검증 오류를 보여주는 깔끔한 방법입니다. 오류 메시지를 데이터 속성에 저장하고, content가 이를 읽게 하고, 표시하려 open()을 호출하세요. 오류가 없을 때 툴팁을 막으려 open 핸들러에서 false를 반환하세요. 빨간 오류 스타일링에는 tooltipClass를 쓰세요.

jquery-ui
<!-- Show validation errors as tooltips -->
<form id="form">
  <input id="email" type="text" placeholder="Email">
  <input id="submit" type="submit" value="Submit">
</form>

<script>
  $("#form").tooltip({
    items: "input",
    content: function () {
      return $(this).data("error") || "";
    },
    position: { my: "left top", at: "left bottom+5" },
    tooltipClass: "error-tooltip",
    open: function (event, ui) {
      var el = $(event.originalEvent.target);
      if (!el.data("error")) return false;  // don't show if no error
    },
  });

  $("#submit").on("click", function (e) {
    var email = $("#email").val();
    if (!email.includes("@")) {
      e.preventDefault();
      $("#email").data("error", "Please enter a valid email")
                 .tooltip("open");
    }
  });
</script>
19

이펙트

코어 이펙트

jQuery UI가 jQuery의 show/hide/toggle을 이름 붙은 이펙트로 확장하고 숨김이 아닌 애니메이션용 .effect() 메서드를 추가합니다. 각각 옵션 객체, 지속 시간, 콜백을 받습니다. 'transfer'가 이전 요소 외곽선을 만듭니다 — 장바구니로 드래그 애니메이션에 유용합니다.

jquery-ui
// Built-in effects (beyond jQuery's show/hide/toggle)
$("#box").hide("fade", {}, 1000);    // fade out
$("#box").show("slide", {}, 500);    // slide in
$("#box").toggle("explode", {}, 800); // explode toggle
$("#box").effect("bounce", { times: 3 }, 300);

// Available effect names:
// blind, bounce, clip, drop, explode, fade, fold,
// highlight, puff, pulsate, scale, shake, size, slide, transfer

이징 함수

jQuery UI의 effects core가 jQuery 기본 'swing'과 'linear' 외에 로버트 페너 이징 함수 약 30개를 더합니다. 어떤 .animate() 호출에서든, show/hide/toggle의 easing 옵션에서든, 또는 세 번째 인수로 쓰세요. 'easeOutBounce'와 'easeOutElastic'이 장난스러운 UI에 인기입니다.

jquery-ui
// jQuery core provides: swing (default), linear
// jQuery UI adds ~30 more easing functions
$("#box").animate({ width: 500 }, 1000, "easeInOutBounce");

// Available easings (subset):
// easeInQuad, easeOutQuad, easeInOutQuad
// easeInCubic, easeOutCubic, easeInOutCubic
// easeInQuart, easeOutQuart, easeInOutQuart
// easeInExpo, easeOutExpo, easeInOutExpo
// easeInBack, easeOutBack, easeInOutBack
// easeInBounce, easeOutBounce, easeInOutBounce
// easeInElastic, easeOutElastic, easeInOutElastic

이펙트가 있는 show/hide/toggle

show/hide/toggle에 첫 인수로 이펙트 이름을 전달하면 애니메이션됩니다. 두 번째 인수가 옵션 객체입니다(이펙트에 따라 direction, distance, percent 등). 세 번째가 지속 시간, 네 번째가 콜백입니다. 숨겨진 요소의 이펙트도 show()로 동작합니다.

jquery-ui
// show with an effect
$("#box").show("drop", { direction: "left" }, 500);

// hide with an effect
$("#box").hide("puff", {}, 500);

// toggle with an effect
$("#box").toggle("scale", { percent: 0 }, 500);

// With a callback
$("#box").hide("blind", 500, function () {
  console.log("Animation complete");
});

// Direction option (where applicable)
$("#box").hide("slide", { direction: "up" });

색 애니메이션

jQuery 코어는 색을 애니메이션할 수 없습니다 — jQuery UI의 effects core가 이를 추가합니다. backgroundColor, color, borderColor가 애니메이션 가능해집니다. switchClass와 toggleClass가 지속 시간을 받아 클래스 사이를 부드럽게 전환하며 바뀐 모든 CSS 프로퍼티를 보간합니다.

jquery-ui
// jQuery UI extends animate() to support colors
$("#box").animate({
  backgroundColor: "#ff0000",
  color: "#ffffff",
  borderColor: "#000000",
}, 1000);

// Animate through the theme states
$("#box").animate(
  { backgroundColor: $.Color("#0a0") },
  { duration: 500 }
);

// Toggle class with smooth transitions
$("#box").switchClass("old-class", "new-class", 500);
$("#box").toggleClass("active", 500);  // duration = animated

클래스 트랜지션

addClass, removeClass, toggleClass가 jQuery UI에서 선택적 지속 시간 인수를 얻습니다 — 상태 사이에서 다른 모든 CSS 프로퍼티가 부드럽게 애니메이션됩니다. switchClass가 두 클래스 사이를 명시적으로 전환합니다. 테마 상태 사이의 애니메이션 가장 깔끔한 방법입니다.

jquery-ui
// Add/remove classes with animation
$("#box").addClass("highlight", 500);    // animate to new class
$("#box").removeClass("highlight", 500);
$("#box").toggleClass("highlight", 500);

// switchClass: smoothly transition from one class to another
$("#box").switchClass("state-default", "state-active", 500);

// All accept a callback
$("#box").addClass("expanded", 500, function () {
  console.log("Done expanding");
});

이펙트 메서드 참조

.effect()는 가시성을 바꾸지 않고 이름 붙은 이펙트를 적용합니다(shake, bounce, pulsate는 순수 이펙트). .transfer()가 한 요소에서 다른 요소로 상자 외곽선을 애니메이션합니다 — '장바구니에 담기' 피드백의 클래식입니다. 프로퍼티별 이징 배열로 다른 프로퍼티가 다른 이징을 쓰게 할 수 있습니다.

jquery-ui
// .effect() — run an effect without hiding
$("#box").effect("shake", { times: 3 }, 300);

// .transfer() — animate a transfer outline to another element
$("#product").effect("transfer", { to: "#cart" }, 500);

// .animate() with colors and easing
$("#box").animate({ left: 200, opacity: 0.5 }, "slow", "easeOutBounce");

// Custom animation with step
$("#box").animate({
  width: ["toggle", "swing"],   // [value, easing] per property
  height: ["toggle", "linear"],
}, 1000);
20

ThemeRoller

ThemeRoller 기본

ThemeRoller는 커스텀 jQuery UI 테마를 만드는 공식 웹 앱입니다. 실시간 미리보기로 색, 폰트, 모서리 반경, 텍스처를 조정한 뒤 테마된 CSS와 이미지 스프라이트가 담긴 ZIP을 내려받으세요. 미리 만든 테마(smoothness, ui-lightness 등)도 CDN에서 제공됩니다.

jquery-ui
<!-- Use a prebuilt theme from the CDN -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">

<!-- Or a custom theme from ThemeRoller (jqueryui.com/themeroller) -->
<!-- 1. Visit the ThemeRoller app -->
<!-- 2. Customize colors, fonts, corner radius, etc. -->
<!-- 3. Download the generated CSS file -->
<link rel="stylesheet" href="my-custom-theme/jquery-ui.css">

CSS 프레임워크 클래스

CSS 프레임워크는 JavaScript 위젯과 독립적입니다 — 위젯 초기화 없이 jQuery UI 스타일과 어울리도록 자신의 마크업에서 ui-widget, ui-widget-header, ui-widget-content와 상태 클래스(ui-state-default, ui-state-hover, ui-state-active)를 쓰세요.

jquery-ui
<!-- The jQuery UI CSS framework is reusable for custom markup -->
<div class="ui-widget">
  <div class="ui-widget-header ui-corner-top">
    <h3>Panel Header</h3>
  </div>
  <div class="ui-widget-content ui-corner-bottom">
    <p>Panel content with themed styling.</p>
    <button class="ui-button ui-widget ui-state-default ui-corner-all">
      <span class="ui-icon ui-icon-gear"></span> Action
    </button>
  </div>
</div>

테마 변수 & 구조

모든 테마가 같은 클래스 집합을 다른 색과 텍스처로 정의합니다. ui-state-highlight(노랑)는 공지용이고, ui-state-error(빨강)는 오류용입니다. 모서리 클래스(ui-corner-all, ui-corner-top 등)가 border-radius를 테마 가능하게 합니다 — ThemeRoller가 한 번에 모두 설정합니다.

jquery-ui
/* ThemeRoller generates CSS with these key classes */
.ui-widget {
  font-family: Arial, sans-serif;   /* font family */
  font-size: 1em;                    /* base font size */
}
.ui-widget-content { border: 1px solid #aaa; background: #fff; color: #222; }
.ui-widget-header  { border: 1px solid #aaa; background: #ccc; color: #222; }
.ui-state-default  { border: 1px solid #d3d3d3; background: #e6e6e6; }
.ui-state-hover    { border: 1px solid #999;    background: #dadada; }
.ui-state-active   { border: 1px solid #aaa;    background: #fff; }
.ui-state-focus    { border: 1px solid #999;    background: #dadada; }
.ui-state-highlight { border: 1px solid #fcefa1; background: #fbf9ee; }
.ui-state-error     { border: 1px solid #cd0a0a; background: #fef1ec; }
.ui-corner-all { border-radius: 4px; }  /* themable radius */

커스텀 테마 오버라이드

base 테마를 로드한 뒤 더 높은 명시도의 CSS로 오버라이드하세요. 작은 조정에는 ThemeRoller를 다시 돌리는 것보다 빠릅니다. 프레임워크 클래스(ui-widget-header, ui-state-default 등)를 타깃하면 모든 위젯이 한 번에 재스타일링됩니다. 플랫하고 현대적인 모양을 위해 모서리 반경을 제거하세요.

jquery-ui
/* Load the base theme first */
@import url("https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css");

/* Override specific elements */
.ui-widget-header {
  background: linear-gradient(to bottom, #2c3e50, #34495e);
  color: #ecf0f1;
}
.ui-state-default {
  background: #3498db;
  border-color: #2980b9;
  color: #fff;
}
.ui-state-hover { background: #2980b9; }
.ui-state-active { background: #1abc9c; border-color: #16a085; }
.ui-corner-all { border-radius: 0; }  /* sharper look */

런타임 테마 전환

런타임에 테마를 전환하려면 여러 테마 CSS 파일을 로드하고 'disabled' 프로퍼티를 토글하세요 — 활성된 것만 적용됩니다. 선택은 localStorage에 지속하세요. 위젯이 즉시 새 스타일을 반영합니다. 단일 CSS 해법은 href 속성을 교체하는 것입니다.

jquery-ui
<!-- Two theme stylesheets; toggle the disabled attribute -->
<link id="theme-light" rel="stylesheet"
      href="themes/ui-lightness/jquery-ui.css">
<link id="theme-dark" rel="stylesheet"
      href="themes/ui-darkness/jquery-ui.css" disabled>

<script>
  function switchTheme(name) {
    $("#theme-light").prop("disabled", name !== "light");
    $("#theme-dark").prop("disabled", name !== "dark");
    localStorage.setItem("theme", name);
  }

  // Restore on load
  $(function () {
    var saved = localStorage.getItem("theme") || "light";
    switchTheme(saved);
  });
</script>

특정 위젯 테마

위젯별 클래스(ui-datepicker, ui-dialog, ui-accordion-header)를 타깃하면 다른 위젯에 영향 없이 개별 위젯을 재스타일링합니다. 1.12+의 'classes' 옵션이 더 깔끔합니다 — 특정 내부 요소에 커스텀 클래스를 추가하며 이를 자신의 CSS에서 스타일링합니다. 가능하면 전역 오버라이드 대신 이를 쓰세요.

jquery-ui
/* Datepicker: style the calendar popup */
.ui-datepicker {
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  border-radius: 0;
}
.ui-datepicker .ui-state-highlight { /* today */ background: #ffd; }
.ui-datepicker .ui-state-active {    /* selected */ background: #2c3e50; }

/* Dialog: remove the default rounded corners */
.ui-dialog { border-radius: 0; box-shadow: 0 8px 30px rgba(0,0,0,0.3); }

/* Accordion: modernize the headers */
.ui-accordion .ui-accordion-header {
  background: #f5f5f5;
  border: none;
  border-bottom: 1px solid #ddd;
  font-weight: bold;
}

/* Use the 'classes' option (1.12+) for per-widget theming */
$("#dialog").dialog({
  classes: { "ui-dialog": "my-dialog", "ui-dialog-titlebar": "my-title" },
});

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.