Skip to content

jQuery UI チートシート

jQuery の上に構築された、厳選された UI インタラクションとウィジェットのセット。

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)をインポートして tree-shaking できます。フルの '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' の getter/setter、'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 を読み込みましょう。

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

要素をドラッグ可能にするのは 1 回の呼び出しです。以後、要素はマウスで動かせます。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' は動きを 1 軸に限定し、'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
});

Drag のイベント

ドラッグ中に 3 つのイベントが発火します:'start'(開始時に 1 回)、'drag'(移動中は継続的に)、'stop'(終了時に 1 回)。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' は、入力や 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' により、十分近いとき draggable がターゲット要素に整列するようジャンプします。'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 は、ドラッグされた要素を受け付けるターゲット領域を定義します。draggable がその上で解放されると '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' がどの draggable を許すかフィルタします — セレクタか関数です。'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
});

Drop のイベント

5 つのイベントがドロップのライフサイクル全体をカバーします。'activate'/'deactivate' は一致するドラッグの開始/終了時に発火し、'over'/'out' は draggable がゾーンに入る/出るとき発火し、'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' はセレクタ文字列か、真偽値を返す関数にできます。関数はドラッグされた要素を受け取り、各候補に対して動くため、データ属性や計算された状態のような実行時ロジックを適用できます。受け付けられない draggable は 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(draggable がゾーンの上にあるとき表示)を組み合わせ、ユーザーへ明確なフィードバックを与えましょう。drop ハンドラでは、通常 draggable を 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)の角に現れます。ハンドルが正しくアンカーするため、要素には位置決め(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
});

Resize のイベント

draggable と同様、resize は start/resize/stop を発火します。ui オブジェクトは 'size'(width、height)と 'position'(left、top)を持ちます。北か西の縁からのリサイズでは、size と position の両方が変わります。ライブプレビューのような依存する 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(数値か、現在の比率を固定する boolean の 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
});

Select のイベント

イベントは選択のライフサイクル中に発火します:ドラッグ中の '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
});

Sort のイベント

重要なイベント:'start'/'stop' がソートを挟みます。'change' はドラッグ中にアイテムの位置が変わったとき発火します。'update' は最終順序が開始時と異なるときだけ発火します — ここで新しい順序を永続化しましょう。多くは toArray()(順にアイテム ID を返す)経由です。

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

placeholder は、アイテムが着地する場所に示される空のスペースです — 明確なドロップフィードバックのため整形しましょう。アイテムの高さがまちまちなら 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" });

Sort のメソッド

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 は header + content 要素のペアを期待します(header が先に来ること)。デフォルトでは一度に 1 セクションだけが開きます。デフォルトの header 要素は h3 ですが、header オプションで変えられます。コンテンツパネルが各 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' を設定すれば全パネルを閉じられます(デフォルトは 1 つ開くことを強制します)。'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 オブジェクトが、両イベントの古い/新しい header と panel 要素を与えます。

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 が閉じている(header)ときと開いている(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() を呼び、ウィジェットが再 bind されましょう。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' へ文字列の単純な配列を渡しましょう。ウィジェットがユーザーのタイピングに合わせ部分文字列でフィルタします。候補はドロップダウンに現れ、選ぶと入力が埋まります。リッチな表示のため、リストは {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 オプションが高速なタイピングを debounce します。

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 を使って入力を基準にメニューの配置を設定します。appendTo は、入力がオーバーフローの問題のある絶対配置コンテナの中にあるときに有用です。

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,
});

カスタムのソース関数

関数の source が完全な制御を与えます — キャッシュ、カスタムフィルタリング、複数エンドポイントの組み合わせに有用です。空であっても、配列で response(results) を MUST で呼びましょう。各アイテムは 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 は、ユーザーが候補を移動するとき(キーボードかホバー)発火します。select はアイテムが実際に選ばれたとき発火します。change は blur で発火し、最終値がソースに存在するか検証する適切な場所です。false を返すとデフォルトの入力充填の挙動が阻止されます。

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 ウィジェットが、jQuery UI のスタイリングでクリック可能な任意の要素(button、input[type=submit]、a)をテーマ化します。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' でプログラム的にテキストを設定でき、実行時に変わるとき(Start/Stop のトグルなど)に有用です。

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(Radio/Checkbox グループ)

buttonset が radio ボタンや checkbox を、視覚的に連結した単一のツールバーへグループ化します。jQuery UI 1.12+ では、buttonset は非推奨になり、より柔軟で任意の入力タイプで動く controlgroup() が推奨です。各入力には一致するラベルが必要です。

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 のメソッド

option メソッドで、実行時に label、icon、disabled 状態を変えましょう — 「送信」→「読み込み中...」のような状態を持つボタンに典型的です。refresh メソッドが要素の状態を再読み込みします(プログラム的にトグルされた checkbox に有用)。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

入力のクリックかフォーカスでカレンダーのポップアップが開きます。選択された日付がテキストとして入力を満たします。カレンダーは現在の月を示し、前/次の月へのナビゲーション矢印があります。デフォルトの日付は米国形式(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' が 4 桁の年を意味します(y が多いのは意図的です)。Date を同じトークンで文字列へ変換するには formatDate() メソッドを、逆には 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

min/max の日付と範囲

日付範囲のピッカーには、2 つの datepicker をリンクさせましょう:開始が選ばれたら終了の 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 ロケールの regional ファイルを同梱します。ファイルを読み込み、$.datepicker.regional['fr'] で適用しましょう。個々の文字列をインラインで上書きすることもできます。regional ファイルが月名、曜日名、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 とイベント

常に見えるインラインカレンダーには、入力の代わりに div へ datepicker を適用しましょう — 予約インターフェースに最適です。日付が選ばれると onSelect が、月を移動すると onChangeMonthYear が発火します。プログラム的な制御には Date オブジェクトで getDate/setDate が機能します。

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: handler)を受け付けます。ハンドラ内では '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 */ },
});

モーダルと確認ダイアログ

1 回限りの確認には、動的に構築した要素からダイアログを作りましょう。modal のオーバーレイがページの残りとの操作を防ぎます。ダイアログが消されたとき 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 によりコンテンツをロードし、ネストしたウィジェットを初期化しましょう。次の open が新鮮になるよう、close で必ずコンテンツを消去します。moveToTop が z-index でダイアログを他より上に持ち上げます — 積み重ねたダイアログに有用です。isOpen が条件分岐のための真偽値 getter です。

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)。value は 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 の upload progress イベントで、転送バイト数に基づき 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 イベントとカスタムラベル

value の更新のたびに change が、100% で complete が発火します — どちらも動的なスタイリングやラベルに有用です。パーセンテージのテキストを示すには、バーの上に絶対配置のラベルを加えましょう。同期を保つため、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 テーマ化された版へ置き換えます。ネイティブの全機能(selected、disabled の option)に対応し、アイコン、カスタム描画、クロスブラウザで一貫したスタイリングを加えます。背後の 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 幅が使われ、数値なら明示的なピクセルです。デフォルトの幅は最も長い option に自動的に合います。position がメニューをボタンを基準に配置します。appendTo は、dialog や iframe 内の selectmenu に有用です。

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 が主イベントです — ユーザーが別の option を選んだとき発火します。ui.item.value が option の 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
  },
});

カスタム描画

_renderItem をオーバーライドすれば、各 option にアイコン、説明、カスタム HTML を加えられます。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 の option を追加・削除・変更した後は必ず 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 と無効な option

Selectmenu はネイティブの <optgroup> 要素を尊重します — 適切なテーマ化付きで、選択不可のグループヘッダーとして描画されます。個々の option の 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 で設定しましょう — 水平スライダーは幅、垂直スライダーは高さです。

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

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

Slider のオプション

2 ハンドルのレンジスライダーには '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 は解放後と、プログラム的な option 変更で発火します。値の永続化にはこちらを使いましょう。

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
  },
});

レンジスライダー

2 ハンドルのレンジスライダーは、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 での明示的な高さが必要です — 幅は交差軸に適用されます。ハンドルが左右ではなく上下に動きます。レンジの色付けは同じように機能します。オーディオミキサー、イコライザー、垂直の向きがより自然な任意の 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) で 1 ハンドルを設定し、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 が数値入力のための上下ボタンをテキスト入力へ加えます。ユーザーは直接タイプするか、ボタンをクリックするか、矢印キーを使えます。ボタンの長押しで刻みが加速します。入力の value は変化のたびに数値としてパースされます。

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 で発火し、入力が有効な数値としてパースできないなら 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() は引数なしでは getter、引数ありでは検証を通る setter です。カスタムの spin ハンドラで、時刻、色、カスタム単位のような非数値の spinner を作れます。

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 をオーバーライドすれば、小数以外の値のための spinner が作れます — hex の色、時刻、角度、任意のカスタム単位。_parse が入力テキストを数値へ変換し、_format が表示のために逆変換します。ドメイン固有の入力で 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' でホバー起動のタブが作れます。

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 Tabs

タブの 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() を呼び、ウィジェットが新しい構造を再 bind するようにしましょう。

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 オプションが現在のタブの getter と setter の両方です — プログラム的な切り替えに使いましょう。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 属性の内容がツールチップのテキストになります。ツールチップはホバーで現れ、マウスアウトで消えます。デフォルトで滑らかなフェードのアニメーション付きです。

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

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

Tooltip のオプション

動的なツールチップの HTML を生成するには、'content' を関数としてオーバーライドしましょう(データ属性や 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

Effects

コアの Effects

jQuery UI は jQuery の show/hide/toggle を名前付きのエフェクトで拡張し、非表示以外のアニメーションのための .effect() メソッドを加えます。それぞれがオプションオブジェクト、duration、コールバックを受け付けます。'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 個の Robert Penner のイージング関数を加えます。任意の .animate() 呼び出し、show/hide/toggle の easing オプション、第 3 引数として使えます。遊び心のある UI には 'easeOutBounce' と 'easeOutElastic' が人気です。

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 の最初の引数にエフェクト名を渡せばアニメーションします。第 2 引数がオプションオブジェクトです(エフェクトに応じて direction、distance、percent など)。第 3 が duration、第 4 がコールバックです。隠れた要素へのエフェクトは 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 は duration を受け付け、クラス間を滑らかに遷移し、変わったすべての 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 から省略可能な duration 引数を得ます — 状態間で異なるすべての CSS プロパティが滑らかにアニメーションします。switchClass が 2 つのクラス間を明示的に遷移させます。テーマ化された状態間のアニメーションの最もきれいな方法です。

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 メソッドのリファレンス

.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 テーマを構築する公式の Web アプリです。ライブプレビューで色、フォント、角丸、テクスチャを調整し、テーマ化された 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(赤)がエラー用です。corner クラス(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 */

カスタムテーマの上書き

ベーステーマを読み込み、より高い詳細度の 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.