시작하기
CDN 설치
jQuery UI는 jQuery 코어에 의존합니다 — 항상 jquery-ui.js 전에 jQuery를 로드하세요. CSS는 기본 테마를 제공하며 Datepicker와 Dialog 같은 위젯이 올바르게 표시되려면 필수입니다. 1.13.x 버전은 jQuery 1.8+를 지원합니다.
<!-- 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 테마는 별도로 임포트해야 합니다.
# 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 끝에 두세요.
$(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를 쓰세요.
// 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 뒤에 로드하세요.
<!-- 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 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 */Draggable
기본 Draggable
요소를 드래그 가능하게 만드는 것은 한 번의 호출입니다. 그러면 마우스로 요소를 옮길 수 있습니다. ui-widget-content 클래스가 기본 테마 스타일을 적용합니다. Draggable이 위치를 상속합니다 — 필요에 따라 relative/absolute가 적용됩니다.
<!-- 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'은 원본 대신 복사본을 드래그합니다.
$("#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'에서 무거운 작업은 성능을 해칩니다.
$("#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 같은 요소에서 드래그를 막습니다.
<!-- 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'와 결합하면 레이아웃 에디터나 대시보드를 위한 정밀하고 스냅된 배치를 만들 수 있습니다.
// 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'. 요소가 정렬되어야 하는 다이어그램 도구나 대시보드 레이아웃에 유용합니다.
$(".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,
});Droppable
기본 Droppable
Droppable이 드래그된 요소를 받아들이는 대상 영역을 정의합니다. 드래그 요소가 그 위에서 놓이면 'drop' 콜백이 발생합니다. ui.draggable 프로퍼티가 드래그된 요소의 참조를 줘 이동하거나 처리할 수 있습니다.
<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 이벤트를 받는 것을 막아 중첩 드롭 존에 유용합니다.
$("#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'은 성공적인 놓기에서만 발생합니다. 점진적 시각 피드백에 쓰세요.
$("#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 이벤트를 트리거하지 않습니다.