Skip to content

jQuery チートシート

高速で小さく、機能豊富な JavaScript ライブラリ。

01

はじめに

jQuery の読み込み

高速でキャッシュされたロードのため、jQuery は CDN 経由で読み込みましょう。圧縮版(.min.js)は本番向けで、非圧縮版はデバッグ向けです。CDN に届かない場合に備え、ローカルのフォールバックを必ず用意しましょう。npm なら、jQuery をモジュールとしてインポートできます — Webpack/Vite のようなバンドラに有用です。jQuery 3.7.x が現在のラインで、古い IE はもうサポートされません。

jquery
<!-- Production (CDN, minified) -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<!-- Development (CDN, uncompressed) -->
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<!-- Fallback: load local if CDN fails -->
<script>
window.jQuery || document.write(
  '<script src="js/jquery-3.7.1.min.js"><\/script>'
)
</script>

<!-- npm install -->
<!-- npm install jquery -->

Document Ready

DOM を操作するコードは $(document).ready() で包み、DOM ツリーのパース後にだけ実行させましょう(画像は待ちません)。$(fn) が省略形です。<script> が <body> の末尾にあれば、DOM は既に利用可能なため ready は省けます。jQuery の ready は DOMContentLoaded と似ています — 画像/iframe を待つ window.load の前に発火します。

jquery
// run code after DOM is fully parsed
$(document).ready(function () {
  console.log('DOM ready')
})

// shorter equivalent
$(function () {
  console.log('DOM ready')
})

// modern preferred (no ready needed at end of body)
// <script> at the end of <body> runs after DOM exists

// pass a function to $ — jQuery treats it as ready handler
$(function () {
  $('.btn').on('click', function () {
    alert('clicked')
  })
})

jQuery オブジェクト($)

$ は単なる jQuery の別名です — どちらも同じように機能します。関数としての $ は要素を選択し(jQuery コレクションを返す)、名前空間としての $.foo はユーティリティメソッドを提供します。他のライブラリが $ を使っているなら、$.noConflict() で解放しましょう。jQuery を使い続けることも、ready のコールバックへ $ を渡しローカルの別名にすることもできます。

jquery
// $ is an alias for jQuery
console.log($ === jQuery)  // true

// $ as a function: select elements
$('p')             // all paragraphs
$('#main')         // element with id main
$('.btn.primary')  // elements with class btn and primary

// $ as a namespace: utility methods
$.each([1, 2, 3], function (i, v) { console.log(i, v) })
$.extend({}, defaults, options)
$.type([])         // 'array'

// noConflict: release $ back to other libraries
$.noConflict()
jQuery(function ($) { /* $ available here */ })

メソッドのチェーン

ほとんどの jQuery メソッドは同じ jQuery コレクションを返すため、呼び出しをチェーンできます — jQuery の看板機能です。トラバーサルのメソッド(.find()、.filter())の後に、前のセットへ戻るには .end() を使いましょう。インデントでチェーンされたトラバーサルが読みやすくなります。長すぎるチェーンは避けましょう — デバッグが難しくなります。チェーン不可のメソッド(.width() の getter など)では、コレクションではなく値を返すためチェーンが切れます。

jquery
// most methods return the jQuery object, enabling chains
$('.box')
  .addClass('active')
  .css('color', 'red')
  .slideDown(300)
  .text('Hello')

// break across lines for readability
$('#nav')
  .find('.item')
    .addClass('highlight')
    .end()
  .find('.link')
    .attr('target', '_blank')

// .end() pops the current filter back to previous set

No-Conflict モード

$.noConflict() は $ の制御を、最初に定義したライブラリへ返します。呼び出し後は、完全な jQuery 名を使うか、jQuery をカスタム変数へ代入しましょう。IIFE のパターン (function($){...})(jQuery) が、グローバルの $ を他のライブラリに残したまま、モジュール内で $ をローカルの別名として保つクラシックな方法です — WordPress とレガシー環境では不可欠です。

jquery
// release $ to other libraries (e.g., Prototype)
$.noConflict()

// use jQuery full name
jQuery('.btn').on('click', function () { /* ... */ })

// or assign jQuery to a custom alias
const jq = $.noConflict()
jq('.btn').hide()

// IIFE pattern: keep $ inside a local scope
(function ($) {
  $('.btn').on('click', function () { /* ... */ })
})(jQuery)
02

セレクタ

基本のセレクタ

jQuery は CSS セレクタを使います(querySelectorAll とほぼ互換)。重要な 3 つ:タグ名、#id、.class。カンマでセレクタを結合します(和集合)。#id が最速です(getElementById を使う)。ユニバーサルの * は遅いので、大きな文書では避けましょう。セレクタの結果は常に jQuery コレクション(配列風)であり、0 個でも 1 個でもマッチします。

jquery
// element selector
$('div')          // all <div> elements
$('p')            // all <p> elements

// id selector
$('#header')      // element with id="header"

// class selector
$('.btn')         // all elements with class="btn"
$('.btn.primary') // .btn AND .primary

// multiple (comma = OR)
$('div, p, .btn') // divs, paragraphs, and .btn

// universal
$('*')            // all elements (slow — avoid)

階層と結合子

結合子が関係を記述します:空白(子孫)、>(直接の子)、+(隣接兄弟)、~(一般兄弟)。右から左への評価により、$('ul li') は最初にすべての <li> を見つけ、次に <ul> の内側のものへ絞り込みます — そのため右側の具体的なセレクタの方が良く機能します。巨大な文書では深い結合子を避け、$(container).find(...) でコンテナへスコープするとパフォーマンスが向上します。

jquery
// descendant: space (any depth)
$('ul li')        // <li> anywhere inside <ul>

// child: > (direct children only)
$('ul > li')      // <li> directly inside <ul>

// adjacent sibling: + (immediately next)
$('h2 + p')       // <p> right after <h2>

// general sibling: ~ (all following siblings)
$('h2 ~ p')       // all <p> siblings after <h2>

// multiple levels
$('#nav .item > a span')

属性セレクタ

属性セレクタは属性値で要素を対象にします:[attr](存在)、[attr=val](完全一致)、[attr^=val](前方一致)、[attr$=val](後方一致)、[attr*=val](部分一致)、[attr~=val](単語)。安全のため値は引用符で囲みましょう。[attr!=val] は jQuery 独自の拡張です(CSS 準拠には .not('[attr=val]') を)。フォーム(input タイプ)、リンク(href パターン)、data-* 属性に有用です。

jquery
// has attribute
$('[href]')                 // any element with href
$('[data-id]')              // any element with data-id

// exact value
$('[type="text"]')          // type="text"
$('[href="https://example.com"]')

// substring matches
$('[href^="https"]')        // starts with "https"
$('[href$=".pdf"]')         // ends with ".pdf"
$('[href*="example"]')      // contains "example"

// whitespace-separated word
$('[class~="active"]')      // class contains word "active"

// inequality (jQuery extension, not CSS)
$('[href!="https://x.com"]')

フォームと Input のセレクタ

フォームの疑似セレクタ(:input、:text、:checked など)は jQuery の拡張です — CSS の一部ではないため、querySelectorAll の高速パスを使えません。大きなフォームのパフォーマンスには、$(':text') の代わりに $('input[type=text]') を使いましょう。:checked と :selected がフォーム状態の読み取りに不可欠です。これらは動的で、アクセスのたびに再評価されます。

jquery
// :input matches all form controls
$(':input')         // input, textarea, select, button

// by type
$(':text')          // <input type="text">
$(':password')
$(':checkbox')
$(':radio')
$(':submit')
$(':file')

// by state
$(':checked')       // checked checkbox/radio or selected option
$(':selected')      // selected <option>
$(':disabled')
$(':enabled')
$(':focus')

// combined with class
$('input.required:visible')

フィルタとコンテンツセレクタ

フィルタが選択を狭めます::first/:last、:even/:odd(0 起点インデックス)、:eq(n)、:gt(n)、:lt(n)。コンテンツフィルタ(:contains、:has、:empty、:parent)は内容に基づき一致します。:visible と :hidden は offsetWidth/Height と CSS に基づきます(注意:visibility:hidden の要素は jQuery 3+ では :hidden です。以前は :visible でした)。これらの多くは jQuery の拡張であるため、パフォーマンスのために .filter()、.first()、.eq() メソッドを推奨します。

jquery
// basic filters
$('li:first')         // first <li>
$('li:last')          // last <li>
$('li:even')          // even-indexed (0, 2, 4...)
$('li:odd')           // odd-indexed
$('li:eq(2)')         // 3rd <li> (0-indexed)
$('li:gt(2)')         // <li> after index 2
$('li:lt(2)')         // <li> before index 2

// content filters
$('div:contains("Hello")')  // divs containing text "Hello"
$('div:empty')              // divs with no children
$('div:has(p)')             // divs containing <p>
$('div:parent')             // divs that have children

// visibility
$(':visible')
$(':hidden')
03

イベント

.on() によるイベントの bind

.on() がモダンなオールインワンのイベント binder です(.bind/.delegate/.live を置き換えます)。イベント名とハンドラを渡します。ハンドラ内の 'this' は DOM 要素です(jQuery ラップではない — 必要なら $(this) で包む)。イベントの名前空間(click.myapp)で、他に影響せず特定のハンドラを unbind できます。複数のイベントが 1 つのハンドラを共有でき(スペース区切り)、個別のハンドラも持てます(オブジェクト形式)。

jquery
// basic binding
$('.btn').on('click', function (e) {
  console.log('clicked!', this)  // 'this' is the DOM element
})

// multiple events, same handler
$('.box').on('mouseenter mouseleave', function () {
  $(this).toggleClass('hover')
})

// multiple events, different handlers
$('.input').on({
  focus: function () { $(this).addClass('focused') },
  blur: function () { $(this).removeClass('focused') }
})

// named events (for targeted unbinding)
$('.btn').on('click.myapp', handler)
$('.btn').off('click.myapp')  // only removes this one

イベント委譲

イベント委譲は、バブリング経由で子からのイベントを受け取る親へ 1 つのハンドラを bind します。.on() の第 2 セレクタ('li')が、どの子がハンドラをトリガーするかフィルタします。利点:N ではなく 1 つのハンドラ、動的に追加された要素の自動対応、低いメモリ。長いリストや SPA には不可欠です。'this' はマッチした子(li)であり、親ではありません。親へのアクセスには e.delegateTarget を使いましょう。

jquery
// delegate: handle events on children, now or future
$('#list').on('click', 'li', function (e) {
  // 'this' is the <li> that was clicked
  $(this).toggleClass('done')
})

// works for <li> added AFTER binding too
$('#list').append('<li>New item (also clickable)</li>')

// WHY: instead of binding to each <li>,
// bind ONCE to the parent; clicks bubble up
// - 1 handler instead of N
// - works for dynamically added elements
// - lower memory, faster setup

イベントオブジェクトとメソッド

イベントオブジェクト(e)が情報と制御メソッドを運びます。preventDefault がブラウザのデフォルト(リンクのナビゲーション、フォーム送信)を止めます。stopPropagation がバブリングを止め、stopImmediatePropagation は同じ要素上の他のハンドラも止めます。e.target が実際にクリックされた要素(子かもしれない)で、e.currentTarget はハンドラを持つ要素(= this)です。.on() の省略可能な第 2 引数でハンドラへデータを渡せます。

jquery
$('.link').on('click', function (e) {
  e.preventDefault()      // stop default action (e.g., navigation)
  e.stopPropagation()     // stop bubbling to parents
  e.stopImmediatePropagation() // stop other handlers on same element

  console.log(e.type)         // 'click'
  console.log(e.target)       // the actual clicked element
  console.log(e.currentTarget) // the element with the handler (= this)
  console.log(e.which)        // mouse button or key code
  console.log(e.pageX, e.pageY) // mouse coordinates

  // data passed via .on(name, data, handler)
})

$('.btn').on('click', { greeting: 'hi' }, function (e) {
  console.log(e.data.greeting)  // 'hi'
})

省略形のイベントメソッド

省略形のメソッド(.click、.focus、.submit など)は、関数付きで呼ばれればハンドラを bind し、なしで呼ばれればイベントをトリガーします。.hover(enter, leave) が mouseenter+mouseleave の便利なラッパーです。これらは .on('event', fn) と等価ですが短いです。一部の省略形(.load、.error)は jQuery 3 で削除されました — 代わりに .on('load', ...) を使いましょう。新規コードにはより明示的で委譲をサポートする .on() を推奨します。

jquery
// shorthand: bind a handler (or trigger if no handler)
$('.btn').click(function () { /* ... */ })
$('.btn').click()  // trigger click

// common shorthands
$('.box').hover(enterFn, leaveFn)   // mouseenter + mouseleave
$('.input').focus(function () { /* ... */ })
$('.input').blur(function () { /* ... */ })
$('.form').submit(function (e) {
  e.preventDefault()
  /* ... */
})
$('.el').mouseenter(fn).mouseleave(fn).mousemove(fn)
$(window).resize(fn).scroll(fn)

// deprecated: .load(), .unload(), .error() (removed in jQuery 3)

トリガーと 1 回限りのイベント

.trigger('event') はハンドラとネイティブの挙動(ナビゲーションなど)の両方を発火させ、.triggerHandler() は jQuery に bind されたハンドラだけを発火させ、ハンドラの戻り値を返します(チェーン不可)。.one() は、最初の実行後に自動で取り除かれるハンドラを bind します — 初回クリックのヒントや 1 回限りのセットアップに最適です。カスタムイベントでコンポーネントが通信できます:$(document).trigger('myapp:ready') と、リスナーが .on('myapp:ready', fn) で購読します。

jquery
// trigger an event programmatically
$('.btn').trigger('click')
$('.btn').click()  // shorthand

// trigger with extra data
$('.box').trigger('custom', [1, 2, 3])

// custom events
$('.box').on('custom', function (e, a, b, c) {
  console.log(a, b, c)  // 1 2 3
})

// fire handler only once
$('.btn').one('click', function () {
  alert('This fires only once')
})

// trigger only native handlers, not custom
$('.link').triggerHandler('click')
04

DOM 操作

コンテンツの取得と設定

.html() は HTML マークアップを扱います(innerHTML のように)— タグがパースされます。.text() はプレーンテキスト用です — タグがエスケープされそのまま表示されます(ユーザー入力への XSS に対してより安全)。.val() はフォームコントロール用(input、select、textarea)です。3 つとも、引数なしで呼ばれれば getter(最初の要素の値を返す)、引数ありなら setter(マッチしたすべての要素に適用)です。setter は (index, oldValue) => newValue のコールバックを受け付けます。

jquery
// .html(): get or set HTML content
$('#box').html()                    // get innerHTML
$('#box').html('<p>Hello</p>')      // set innerHTML

// .text(): get or set text (HTML-escaped)
$('#box').text()                    // get text content
$('#box').text('<p>Not parsed</p>') // displays literally

// setter with callback (index, old value)
$('p').text(function (i, oldText) {
  return i + ': ' + oldText
})

// .val(): form value
$('input').val()                    // get
$('input').val('new value')         // set
$('select').val()                   // get selected value
$('select').val(['a', 'b'])         // multi-select

要素の挿入

要素の作成は $() へ HTML を渡して行います:$('<div class="x">...</div>')。append/prepend は内側へ(末尾/先頭)挿入し、before/after は外側へ(兄弟として)挿入します。「To」のバリアント(appendTo、prependTo、insertBefore、insertAfter)は主語を逆にします — 新しい要素の上でチェーンするのに有用です。新しく挿入された要素は、委譲経由で bind されたイベントハンドラを継承しますが、挿入前に直接 bind されたものは継承しません。

jquery
// create new element
const $li = $('<li class="item">New item</li>')

// add as last child of each matched element
$('ul').append($li)
$('ul').append('<li>Direct string</li>')

// add as first child
$('ul').prepend('<li>First</li>')

// insert before/after matched elements
$('.box').before('<hr>')
$('.box').after('<hr>')

// reverse direction (insert target into container)
$('<p>Hi</p>').appendTo('#main')   // same as $('#main').append(...)
$('<p>Hi</p>').insertBefore('#nav')

削除と置換

.remove() が要素を削除し、そのデータ/イベントを後始末します。.detach() は DOM から取り除きますがデータ/イベントを保持します — 要素を一時的に移動させるのに有用です。.empty() は子を消去しますが要素は残します。.replaceWith() が各要素を新しいコンテンツと交換します。.unwrap() が親を取り除き、要素を一段上げます。子のデータ/イベントが漏れるため、親に .html('') を使うのではなく、必ず .remove() か .detach() を使いましょう。

jquery
// remove element (and its data + events)
$('.box').remove()

// detach: remove but keep events/data (for re-insertion)
const $el = $('.box').detach()
// ... later
$('body').append($el)  // events still work

// empty: remove all children (keep element)
$('.box').empty()

// replace with new content
$('.old').replaceWith('<div class="new">New</div>')

// unwrap: remove parent (keep element)
$('.box').unwrap()

ラップと複製

.wrap() は各要素を個別にラップし、.wrapAll() はセット全体を 1 つのグループとしてラップし、.wrapInner() は内容(要素自体ではない)をラップします。.clone() が深いコピーを作ります — イベントハンドラとデータも複製するには true を渡しましょう(デフォルト false のため、ハンドラはコピー上で発火しません)。.unwrap() が直接の親を取り除きます。これらは、HTML 文字列を書き直さずにマークアップを再構成する強力な道具です。

jquery
// wrap each element in a structure
$('p').wrap('<div class="wrapper"></div>')
// each <p> becomes <div class="wrapper"><p>...</p></div>

// wrap all matched elements together
$('p').wrapAll('<div class="all"></div>')

// wrap inner contents
$('p').wrapInner('<span></span>')
// <p><span>...</span></p>

// clone (with events)
const $copy = $('.box').clone(true)  // true = clone events too
$('body').append($copy)

// unwrap (remove wrapper)
$('.box').unwrap()

反復とフィルタ

.each() が反復します — 'this' は生の DOM 要素で、false を返すと中断し、それ以外では続きます。.map() は新しい jQuery コレクションへ変換し、素の配列へ変えるには .get() を呼びます。.filter() がセレクタかコールバックで絞り込み、.not() が逆です。.is() が真偽値を返します(どれかの要素が一致するか?)— 条件分岐に有用です。.eq(i) での for ループは避け、慣用的な jQuery には .each() や .map() を使いましょう。

jquery
// .each: iterate (this = DOM element, i = index)
$('li').each(function (i, el) {
  console.log(i, this, el)  // el === this
  if (i === 2) return false  // break
  // return true to continue
})

// .map: transform to new array
const ids = $('li').map(function (i, el) {
  return $(el).data('id')
}).get()  // .get() converts to plain array

// .filter: keep matching
$('li').filter('.active').addClass('on')
$('li').filter(function (i) { return i % 2 === 0 })

// .not: remove matching
$('li').not('.active').addClass('off')

// .is: returns boolean (does ANY match?)
if ($('li').is('.active')) { /* at least one is active */ }
05

CSS の操作

CSS プロパティの取得と設定

.css() は計算済みスタイルを取得し(CSS ルールからでも常に解決済みの値)、インラインスタイルを設定します。getter には単一のプロパティ名を渡します(文字列を返す)。setter には (prop, value) か、prop:value のペアのオブジェクトを渡します。プロパティ名は camelCase でも kebab-case でも構いません(後者は引用符が要る)。数値はほとんどのプロパティでデフォルトがピクセルです。レイアウトのための .css() は避けましょう — 保守性のためクラスとスタイルシートを使います。

jquery
// get computed style (first matched element)
$('.box').css('color')           // 'rgb(255, 0, 0)'
$('.box').css('font-size')       // '14px'

// set single property
$('.box').css('color', 'red')

// set multiple properties
$('.box').css({
  color: 'red',
  'background-color': '#eee',  // kebab-case needs quotes
  fontSize: '16px',            // or use camelCase
  marginTop: '10px'
})

// setter with callback (index, old value)
$('div').css('width', function (i, old) {
  return (parseInt(old) + 50) + 'px'
})

クラスの操作

クラスのメソッドが要素のスタイリングの推奨方法です — 表現を CSS に置き、JS に置かないためです。.addClass、.removeClass、.toggleClass はスペース区切りのクラスリストを受け付けます。.toggleClass(name, bool) は真偽値に基づき追加/削除します — 状態駆動の UI に有用です。.hasClass(name) が真偽値を返します(最初の要素だけ確認)。パフォーマンスのため、重要でないスタイリングでは .css() よりクラスがはるかに速いです。変更をまとめブラウザに最適化を許すためです。

jquery
// add class
$('.box').addClass('active')

// remove class
$('.box').removeClass('active')

// toggle (add if absent, remove if present)
$('.box').toggleClass('active')

// toggle based on boolean
$('.box').toggleClass('active', isValid)

// add/remove multiple (space-separated)
$('.box').addClass('active highlighted urgent')
$('.box').removeClass('active highlighted')

// check if has class (boolean)
if ($('.box').hasClass('active')) { /* ... */ }

// callback form (index, hasClass)
$('div').toggleClass('even', function (i) {
  return i % 2 === 0
})

幅と高さ

.width()/.height() = コンテンツボックス(パディング/罫線なし)。.innerWidth()/.innerHeight() = コンテンツ + パディング。.outerWidth()/.outerHeight() = コンテンツ + パディング + 罫線。.outerWidth(true) はマージンを含みます。setter は数値(px)か文字列を取ります。window/document には、ビューポートは $(window)、フルページは $(document) を使いましょう。これらは数値を返すため(.css('width') のような文字列ではない)、計算に便利です。

jquery
// content size (excludes padding, border, margin)
$('.box').width()          // e.g., 200
$('.box').width(300)       // set content width to 300px
$('.box').height()

// inner (content + padding)
$('.box').innerWidth()
$('.box').innerHeight()

// outer (content + padding + border)
$('.box').outerWidth()
$('.box').outerHeight()

// outer including margin
$('.box').outerWidth(true)

// window & document
$(window).width()    // viewport width
$(document).height() // full document height

Position と Offset

.offset() は文書を基準にした {top, left} を返します(絶対位置決めやドラッグ・ドロップに有用)。.position() はオフセットの親(position: relative/absolute/fixed を持つ最も近い祖先)を基準にした座標を返します。.scrollTop()/.scrollLeft() がスクロール位置を取得・設定します — $(window).scrollTop(0) で最上部へスクロールします。.offsetParent() が配置済みの祖先を見つけます。これらはアニメーション、ドラッグ・ドロップ、無限スクロールに不可欠です。

jquery
// .offset(): position relative to document
const off = $('.box').offset()
console.log(off.left, off.top)  // e.g., 100, 50
$('.box').offset({ top: 200, left: 100 })  // set

// .position(): position relative to offset parent
const pos = $('.box').position()
console.log(pos.left, pos.top)

// .scrollTop() / .scrollLeft(): scroll position
$(window).scrollTop()       // how far scrolled down
$(window).scrollTop(0)      // scroll to top
$('.container').scrollTop(100)

// .offsetParent(): nearest positioned ancestor
$('.box').offsetParent()

Scroll と座標

スクロールの処理は、スティッキーなナビ、無限スクロール、スクロール起動のアニメーションで一般的です。$('html, body').animate({scrollTop: n}) が滑らかにスクロールします。パフォーマンスのため、スクロールハンドラを throttle しましょう(1 スクロールで何度も発火します)。isVisible のヘルパーが、要素がビューポート内にあるか確認します — 画像の遅延ロードやアニメーションのトリガーに有用です。モダンな IntersectionObserver は可視性の検出により効率的です。新しいプロジェクトでは検討しましょう。

jquery
// scroll to top smoothly
$('html, body').animate({ scrollTop: 0 }, 500)

// scroll to an element
const top = $('#section').offset().top
$('html, body').animate({ scrollTop: top }, 500)

// detect scroll position
$(window).on('scroll', function () {
  const scrolled = $(window).scrollTop()
  if (scrolled > 100) {
    $('.nav').addClass('fixed')
  } else {
    $('.nav').removeClass('fixed')
  }
})

// check if element is in viewport
function isVisible($el) {
  const t = $el.offset().top
  const h = $el.outerHeight()
  const wTop = $(window).scrollTop()
  const wH = $(window).height()
  return t >= wTop && (t + h) <= (wTop + wH)
}
06

AJAX

$.ajax(完全な制御)

$.ajax が低レベルで完全に制御できるメソッドです。method/HTTP 動詞、data(GET ではクエリとして、POST ではボディとして送られる)、dataType が期待するレスポンスをヒントとして示します(自動パース)。success/error/complete がレガシーなコールバックフックです。beforeSend で xhr を修正できます(ヘッダー追加)。timeout が N ms 後に中断します。モダンなコードでは、success/error のコールバックの代わりに、fetch() か .done()/.fail() の promise 付きの $.ajax を推奨します。

jquery
$.ajax({
  url: '/api/users',
  method: 'GET',                // or 'POST', 'PUT', 'DELETE'
  data: { page: 1, limit: 10 }, // query string or body
  dataType: 'json',             // expected response type
  contentType: 'application/json',
  timeout: 5000,                // ms
  headers: { 'X-Token': 'abc' },
  beforeSend: function (xhr) { /* ... */ },
  success: function (data, status, xhr) {
    console.log('got', data)
  },
  error: function (xhr, status, error) {
    console.error('failed', status, error)
  },
  complete: function (xhr, status) {
    // runs on both success and error
  }
})

省略形:$.get と $.post

$.get と $.post が単純な GET/POST リクエストの省略形です。promise 風のインターフェース(.done/.fail/.always)が success/error のコールバックよりきれいで、複数の .done ハンドラのチェーンもサポートします。JSON のリクエストボディには、contentType: 'application/json' の設定と、JSON.stringify が両方必要です(jQuery はオブジェクトを JSON として自動文字列化しません)。注意:jQuery の promise は Deferred でありネイティブの Promise ではありませんが、ほとんどのケースで同様に機能します。

jquery
// GET request
$.get('/api/users', { page: 1 }, function (data) {
  console.log(data)
}, 'json')

// promise-based (preferred)
$.get('/api/users', { page: 1 })
  .done(function (data) { console.log(data) })
  .fail(function (xhr, status, err) { console.error(err) })

// POST request
$.post('/api/users', { name: 'Alice' })
  .done(function (data) { /* created */ })

// POST JSON
$.ajax({
  url: '/api/users',
  method: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({ name: 'Alice' })
})

要素への HTML ロード

.load() は特殊化された省略形です:URL から HTML を取得し、マッチした要素へ注入します。'url #fragment' の構文でレスポンスの一部(#fragment に一致する部分)だけがロードされます。.load() は、フルリロードなしの部分的なページ更新に最適です — レガシーな SPA で一般的です。デフォルトは GET で、data を渡せば POST です。コールバックは (responseText, status, xhr) を受け取ります。モダンなアプリでは、fetch + 手動の DOM 更新が推奨です。

jquery
<!-- load HTML from server into element -->
<div id="content">Loading...</div>

<script>
$('#content').load('/partials/header.html')

// load a fragment (selector after URL space)
$('#content').load('/page.html #main')

// with callback (response, status, xhr)
$('#content').load('/page.html', function (resp, status, xhr) {
  if (status === 'error') {
    $('#content').html('Failed to load')
  }
})

// POST with data
$('#content').load('/api', { id: 5 })
</script>

getJSON と getScript

$.getJSON は dataType:'json' の $.ajax の省略形です — レスポンスを自動パースします。'?callback=?' のトリックが、クロスドメインのリクエストで JSONP を有効にします(レガシー — 今は CORS を使いましょう)。$.getScript が JavaScript ファイルを取得して実行します — プラグインや分析の遅延ロードに有用です。どちらも jqXHR(promise 風)オブジェクトを返します。今日のクロスドメインリクエストでは、サーバーが CORS ヘッダーを送ることを確保しましょう。JSONP は CORS 以前の回避策で、セキュリティの注意点があります。

jquery
// fetch and parse JSON
$.getJSON('/api/users', { page: 1 })
  .done(function (data) {
    console.log(data.users)
  })
  .fail(function (xhr, status, err) {
    console.error('JSON fetch failed:', err)
  })

// fetch and execute a script
$.getScript('/js/analytics.js')
  .done(function (script, status) {
    console.log('analytics loaded')
    // script is now available
  })
  .fail(function () {
    console.error('script failed')
  })

// JSONP (cross-domain, legacy)
$.getJSON('https://api.example.com/data?callback=?')
  .done(function (data) { /* ... */ })

グローバル AJAX イベントと設定

グローバルの AJAX イベント(ajaxStart、ajaxStop、ajaxComplete、ajaxError、ajaxSuccess)はすべての AJAX リクエストで発火します — グローバルのローダーとエラー処理に最適です。$.ajaxSetup が、以後のすべての AJAX 呼び出しに適用されるデフォルトを設定します(URL ベース、ヘッダー、タイムアウト)。.serialize() がフォームをクエリ文字列へ変え、.serializeArray() が {name, value} オブジェクトの配列を返します — JSON やカスタムペイロードの構築に有用です。状態変更のリクエストには必ず CSRF トークンを含めましょう。

jquery
// global ajax event handlers (bind on document)
$(document)
  .ajaxStart(function () { $('#loader').show() })
  .ajaxStop(function () { $('#loader').hide() })
  .ajaxError(function (e, xhr, settings, error) {
    console.error('AJAX error:', settings.url, error)
  })

// default settings for all AJAX
$.ajaxSetup({
  baseURL: '/api',
  timeout: 10000,
  headers: { 'X-CSRF-Token': $('meta[name=csrf]').attr('content') }
})

// now $.get('/users') -> GET /api/users with the headers
$.get('/users').done(/* ... */)

// serialize a form for AJAX
const data = $('form').serialize()       // "name=Alice&age=30"
const arr = $('form').serializeArray()   // [{name, value}, ...]
07

Effects とアニメーション

基本の Show/Hide

.show()/.hide()/.toggle() が display を変えます。引数なしなら即座に表示/非表示です。duration があれば、width/height/opacity をアニメーションします。'slow' = 600ms、'fast' = 200ms、またはミリ秒の数値です。コールバックはアニメーション完了時に発火します。jQuery のアニメーションはデフォルトで requestAnimationFrame を使います(カクつきなし)。注意:.hide() が display:none を設定し、.show() が元の display 値を復元します。より多くの制御には .animate() を直接使いましょう。

jquery
// instantly show/hide/toggle
$('.box').show()
$('.box').hide()
$('.box').toggle()

// animated (duration in ms or 'slow'/'fast')
$('.box').show(400)         // fade in over 400ms
$('.box').hide('slow')      // ~600ms
$('.box').toggle(300)

// with callback (runs when animation completes)
$('.box').hide(300, function () {
  console.log('hidden')
})

// easing (default 'swing', also 'linear' with plugin)
$('.box').hide({ duration: 300, easing: 'linear' })

フェード

フェードのアニメーションは opacity だけを変えます(display は変わらない)。.fadeTo は特定の opacity へアニメーションします — 要素を完全に隠さず薄くするのに有用です。アニメーションは要素ごとにキューに入るため、.fadeOut().fadeIn() のチェーンは同時ではなく逐次実行されます。並行に実行するには、複数プロパティ付きの .animate() か queue オプションを使いましょう。通知のような opacity 駆動の UI では、show/hide よりフェードが滑らかです。

jquery
// fade in / out / toggle (opacity only)
$('.box').fadeIn(400)
$('.box').fadeOut(400)
$('.box').fadeToggle(400)

// fade to a specific opacity (0.0 - 1.0)
$('.box').fadeTo(400, 0.5)  // 50% opacity

// with callback
$('.box').fadeOut(300, function () {
  // runs after fade out completes
  $(this).remove()
})

// sequence: fade out, then fade in
$('.box')
  .fadeOut(300)
  .fadeIn(300)  // queued automatically

スライド

スライドは高さ(と display)をアニメーションします。.slideDown が要素を明らかにし(display:none から自然な高さへ)、.slideUp が隠し(0 へ折りたたみ、その後 display:none)、.slideToggle が状態を反転させます。アコーディオン、ドロップダウン、折りたたみ可能なパネルに最適です。アコーディオンの挙動(1 つが開くと他を閉じる)には siblings() と組み合わせましょう。スライドが最もよくある jQuery のアニメーションです — 適切な ARIA と共に使えば滑らかでアクセシビリティにも優れます。

jquery
// slide down (reveal) / up (hide) / toggle
$('.panel').slideDown(400)
$('.panel').slideUp(400)
$('.panel').slideToggle(400)

// accordion pattern
$('.accordion .header').on('click', function () {
  $(this).next('.content').slideToggle(300)
       .siblings('.content').slideUp(300)
})

// callback after slide completes
$('.panel').slideUp(300, function () {
  console.log('panel closed')
})

カスタム .animate()

.animate() が、duration の間、数値の CSS プロパティを tween します。漸進的な変更には相対値('+=50')を使いましょう。プロパティ名は MUST で camelCase です(margin-left ではなく marginLeft)。色には jQuery Color プラグインか jQuery UI が必要です — コアの jQuery は数値だけをアニメーションします。オプション形式でより多くの制御が可能です:queue:false で逐次ではなく並行実行。イージングのデフォルトは 'swing'(ease-out)で、'linear' は一定です。多くのプロパティを 1 回の呼び出しでアニメーションできます。

jquery
// animate numeric CSS properties
$('.box').animate({
  width: '+=50',       // relative: add 50px
  height: '300px',
  opacity: 0.5,
  marginLeft: '20px',  // camelCase for hyphenated props
  fontSize: '20px'
}, 800, 'swing', function () {
  console.log('animation done')
})

// options object form
$('.box').animate({
  left: 500
}, {
  duration: 1000,
  easing: 'linear',
  complete: function () { /* done */ },
  queue: false  // run immediately, not queued
})

// NOTE: colors can't be animated without jQuery UI / color plugin

停止とチェーン

.stop() がアニメーションを止めます。(clearQueue, jumpToEnd) で制御できます。stop がなければ、素早いホバーでアニメーションが積み上がります(マウスが去った後も要素が長く動き続ける)— .animate() の前の .stop(true) がこれを防ぎます。.finish() がキューに入ったすべてのアニメーションを即座に最終状態へ飛ばします。.delay(ms) がアニメーションキューへ一時停止を挿入します — 順序付けに有用です。カクつきの蓄積を避けるため、ホバーのアニメーションには必ず .stop() をペアにしましょう。

jquery
// .stop(): stop current animation
$('.box').stop()              // stop, leave at current state
$('.box').stop(true)          // clear queue too
$('.box').stop(true, true)    // clear queue AND jump to end

// prevent animation buildup on rapid hover
$('.box').hover(function () {
  $(this).stop(true).animate({ width: 300 }, 200)
}, function () {
  $(this).stop(true).animate({ width: 100 }, 200)
})

// .finish(): jump all queued animations to end state
$('.box').finish()

// .delay(): pause between queued animations
$('.box')
  .fadeOut(300)
  .delay(500)        // wait 500ms
  .fadeIn(300)
08

Traversing

上へ移動(Parents)

上へのトラバーサル:.parent()(直接の親)、.parents()(document までのすべての祖先)、.parents(selector) はそれをフィルタし、.closest(selector) は上へたどり最初の一致を返します(自分自身を含む — 囲むコンポーネントの検索で最もよく使う)。.parentsUntil(selector) は一致までの祖先を返します(一致は含まない)。.closest() がイベント委譲パターンの頼みの綱です — クリックされた要素から、囲むカード/行/コンポーネントを見つけます。

jquery
// direct parent
$('#item').parent()

// all ancestors (up to <html> or selector)
$('#item').parents()              // all ancestors
$('#item').parents('.container')  // first .container ancestor

// closest ancestor (incl. self) matching selector
$('#item').closest('.box')  // very common - find enclosing box

// parentsUntil: ancestors up to (not including) match
$('#item').parentsUntil('.wrapper')

// offsetParent: nearest positioned ancestor
$('#item').offsetParent()

下へ移動(Children)

.children() は直接の子だけを返し(1 レベル下)、.find() はすべてのレベルを下ります。.find() が最もよくあります — コンテナが与えられれば、一致する子孫を見つけます(フォーム内の全フォームフィールドなど)。直接の子だけで良いなら .children() の方が速いです。.contents() はテキストノードとコメントノードを含みます(テキストや iframe の処理に有用)。どちらもセレクタでフィルタしましょう。文書全体をスキャンしないために、トラバーサルは必ず .find() でスコープします。

jquery
// direct children (optionally filtered)
$('#list').children()             // all direct children
$('#list').children('.item')      // direct children with class .item

// all descendants (filtered)
$('#list').find('li')             // all <li> anywhere inside
$('#list').find('.active')        // all .active descendants

// contents: children including text/comment nodes
$('#box').contents()

// first/last child
$('#list').children().first()
$('#list').children().last()

横へ移動(Siblings)

兄弟のトラバーサル:.siblings()(すべて)、.next()/.prev()(直接)、.nextAll()/.prevAll()(1 方向のすべて)、.nextUntil()/.prevUntil()(一致まで)。セレクタでフィルタしましょう。クラシックなアクティブタブのパターン($(this).addClass('active').siblings().removeClass('active'))が、兄弟の状態をリセットするために siblings を使います。兄弟は同じ親を共有します — 要素が異なる形でネストしていれば兄弟ではありません。

jquery
// all siblings (excluding self)
$('#item').siblings()
$('#item').siblings('.active')  // siblings with class .active

// next/prev: immediate sibling
$('#item').next()
$('#item').prev()

// nextAll/prevAll: all following/preceding siblings
$('#item').nextAll()
$('#item').prevAll('.item')

// nextUntil/prevUntil: siblings up to a match
$('#item').nextUntil('.stop')

// common: highlight active tab
$('.tab').on('click', function () {
  $(this).addClass('active').siblings().removeClass('active')
})

選択のフィルタ

フィルタリングは、DOM を再クエリせずに現在のセットを狭めます。.filter(selector) が一致を残し、.not(selector) が逆です。.has(selector) が、一致する子孫を含む要素を残します。.eq(n) が 1 要素へ減らします(負の n は末尾から数える)。.first()/.last() が便利なラッパーです。.slice(start, end) が範囲を取ります。複雑なセレクタを書く代わりに、トラバーサル後の選択の絞り込みにこれらを使いましょう — 多くの場合より明快で速いです。

jquery
// .filter: keep matching
$('li').filter('.active')
$('li').filter(function (i) { return i % 2 === 0 })  // even index

// .not: remove matching (inverse of filter)
$('li').not('.active')
$('li').not(':first')

// .has: keep elements that contain a descendant
$('div').has('p')  // divs that contain <p>

// .eq: reduce to one element by index
$('li').eq(2)      // 3rd <li> (0-indexed)
$('li').eq(-1)     // last <li>

// .first / .last
$('li').first()
$('li').last()

// .slice: range
$('li').slice(2, 5)  // indices 2, 3, 4

.end() と .addBack() でのチェーン

.end() がトラバーサルのスタックを pop し、前のセットへ戻ります — トラバースした後で元の集合に継続して作業する読みやすいチェーンには不可欠です。.addBack()(旧 .andSelf)が現在のセットと前のセットをマージし、元の要素が以後の操作に参加します。これらで強力な 1 行のチェーンが作れます:子を見つけ、修正し、end() で親へ戻り、親を修正する。トラバーサルの構造が明確になるよう、チェーンはインデントしましょう。

jquery
// .end(): pop back to previous set after a traversal
$('ul')              // [ul]
  .find('li')        // [li, li, li]
    .addClass('item')
    .end()           // back to [ul]
  .addClass('has-items')

// .addBack(): include previous set in current
$('ul')
  .children('li')    // [li, li]
    .addClass('item')
    .addBack()       // [li, li, ul]
  .addClass('related')

// without .addBack, the ul would not get .related
// .andSelf (old name) is deprecated, use .addBack
09

ユーティリティ関数

反復:$.each と $.map

$.each が配列(index, value)かオブジェクト(key, value)を反復します — 引数の順序が Array.forEach と逆なのに注意しましょう。中断するには false を返します。$.map は各アイテムを新しい配列へ変換します(スキップには null を返す)。$.grep が配列をフィルタします。これらは jQuery の ES5 以前の反復ユーティリティです。モダンなコードはネイティブの Array メソッド(forEach、map、filter)をよく使います。$.each を使う主な理由は、プレーンなオブジェクトの反復です(モダン JS では Object.entries)。

jquery
// $.each: iterate arrays or objects (returns the collection)
$.each([10, 20, 30], function (index, value) {
  console.log(index, value)  // 0 10, 1 20, 2 30
  if (value === 20) return false  // break
})

$.each({ a: 1, b: 2 }, function (key, value) {
  console.log(key, value)  // 'a' 1, 'b' 2
})

// $.map: transform to a new array
const doubled = $.map([1, 2, 3], function (value, index) {
  return value * 2  // [2, 4, 6]
})

// return null/undefined to skip
const evens = $.map([1, 2, 3, 4], function (v) {
  return v % 2 === 0 ? v : null  // [2, 4]
})

// $.grep: filter an array
const evens = $.grep([1, 2, 3, 4], function (v) { return v % 2 === 0 })
// [2, 4]

型チェック

$.type が小文字のタイプ文字列を返します(typeof より細かい)。$.isArray、$.isFunction、$.isPlainObject、$.isEmptyObject、$.isWindow、$.isNumeric が便利な真偽値です。$.isPlainObject が、new Date や window のようなインスタンスから素の {} を区別します。$.isNumeric は有限数と数値文字列に true を返します(新しい jQuery では '0x1F' のような hex には false)。モダン JS では Array.isArray と typeof がほとんどをカバーしますが、deep extend の安全のため $.isPlainObject は依然便利です。

jquery
// $.type: detailed type
$.type([])         // 'array'
$.type({})         // 'object'
$.type('hi')       // 'string'
$.type(null)       // 'null'
$.type(undefined)  // 'undefined'
$.type(/regex/)    // 'regexp'

// specific checks (all return boolean)
$.isArray([])           // true
$.isFunction(fn => {})  // true
$.isEmptyObject({})     // true
$.isPlainObject({})     // true (created by {} or new Object)
$.isPlainObject([])     // false
$.isWindow(window)      // true
$.isNumeric('42')       // true (also '0x1F')
$.isNumeric('abc')      // false

// $.isEmptyObject: no own enumerable props
$.isEmptyObject({ a: 1 })  // false

オブジェクトと配列のユーティリティ

$.extend がオブジェクトをマージします — 後のプロパティが前を上書きします。深い(再帰的な)マージには第 1 引数に true を渡しましょう。そうでなければ浅いです。ソースを書き換えないため、最初の引数には必ず {} を渡しましょう。$.merge が配列を連結します(第 1 を書き換えます)。$.inArray は indexOf です(見つからなければ -1)。$.makeArray が配列風のオブジェクト(NodeList、arguments)を本物の配列へ変換します — モダンなコードでは Array.from か spread [...nl] を使いましょう。

jquery
// $.extend: merge objects (mutates first unless deep copy flag)
const defaults = { a: 1, b: 2 }
const options = { b: 3, c: 4 }
const merged = $.extend({}, defaults, options)
// { a: 1, b: 3, c: 4 }  (later overrides earlier)

// deep merge (recurses into nested objects)
const deep = $.extend(true, {},
  { nested: { x: 1, y: 2 } },
  { nested: { y: 3, z: 4 } }
)
// { nested: { x: 1, y: 3, z: 4 } }

// $.merge: combine two arrays (mutates first)
const combined = $.merge([1, 2], [3, 4])  // [1, 2, 3, 4]

// $.inArray: find index (-1 if not found)
const idx = $.inArray(2, [1, 2, 3])  // 1

// $.makeArray: convert array-like to true array
const arr = $.makeArray(document.querySelectorAll('li'))

文字列とデータのユーティリティ

$.trim が空白を剥ぎ取ります(モダン:str.trim())。$.parseHTML が HTML 文字列を DOM ノードの配列へ変換します — 信頼できない入力には $.fn.html より安全です(スクリプト実行を避けます)。$.param がオブジェクトをクエリ文字列へシリアライズします(parse の逆)。$.now は Date.now() です。$.unique は DOM 要素の配列の重複を除きます(今ではめったに不要)。これらのほとんどにネイティブのモダンな等価物があります。今も有用な残りは、AJAX データのための $.param と $.parseHTML です。

jquery
// $.trim: remove leading/trailing whitespace
$.trim('  hello  ')  // 'hello'  (use str.trim() in modern code)

// $.parseHTML: parse string to DOM nodes
const nodes = $.parseHTML('<div><p>Hi</p></div>')
// [div] — array of DOM nodes

// $.parseJSON: parse JSON string (use JSON.parse instead)
const obj = $.parseJSON('{"a":1}')

// $.param: serialize object to query string
$.param({ name: 'Alice', age: 30 })
// 'name=Alice&age=30'
$.param({ tags: ['a', 'b'] })
// 'tags%5B%5D=a&tags%5B%5D=b'

// $.now: current timestamp (Date.now equivalent)
$.now()  // 1700000000000

// $.unique: remove duplicates from DOM element array
$.unique($('.box').get())

データの保存($.data)

$.data / .data() が、要素に紐付いた任意の値を内部キャッシュへ保存します(DOM には見えず、属性アクセスより速い)。.data() は data-* 属性も自動読み込みします(型変換付き:数値、真偽値、JSON)。重要:.data(name, value) はキャッシュへ書くのであって data-* 属性ではありません — 属性自体の更新には .attr('data-name', val) を使いましょう。キャッシュエントリの消去は .removeData です。要素が .remove() されるとキャッシュは片付けられ、リークが防がれます。

jquery
// store data on an element (private, won't appear in DOM)
$.data(document.getElementById('box'), 'key', { count: 1 })

// read it back
const v = $.data(el, 'key')  // { count: 1 }

//.data() method form (more common)
$('.box').data('key', { count: 1 })
$('.box').data('key')        // { count: 1 }

// auto-parses data-* attributes
// <div class="box" data-id="42" data-name="alice"></div>
$('.box').data('id')    // 42 (auto-cast to number)
$('.box').data('name')  // 'alice'

// remove data
$('.box').removeData('key')

// note: .data() does NOT write back to data-* attrs
// use .attr('data-key', val) to update the attribute
10

プラグインと拡張

プラグインの作成

プラグインは $.fn(jQuery のプロトタイプ)を拡張し、コレクション上で呼び出せるようになります。チェーン可能性のため、必ず this(または this 上のメソッドの結果)を返しましょう。プラグインの内側では 'this' が jQuery コレクションで、.each() の内側では 'this' が生の DOM 要素です。jQuery 経由で安全に $ を別名とするため IIFE で包みましょう。$.extend の defaults パターンが、適切なデフォルトを持つオプションを受け付ける標準的な方法です。プラグインは npm 経由か、スタンドアロンのスクリプトとして公開します。

jquery
// basic plugin pattern
(function ($) {
  $.fn.highlight = function (color) {
    // 'this' is the jQuery collection
    return this.css('background', color || 'yellow')
  }
}(jQuery))

// usage
$('.box').highlight('red')
$('.box').highlight()  // default 'yellow'

// options pattern
$.fn.tooltip = function (options) {
  const settings = $.extend({
    position: 'top',
    delay: 200
  }, options)

  return this.each(function () {
    // 'this' is a DOM element here
    // ... tooltip logic ...
  })
}

メソッド付きのプラグイン

ボイラープレートのプラグインパターンは、第 1 引数により dispatch される methods オブジェクトを使います:初期化は $('.c').counter({ start: 5 })、メソッド呼び出しは $('.c').counter('increment')。状態は $.data に置かれます。このパターンは、スライダー、モーダル、datepicker のようなコンポーネント向けに、Vue/React 以前の時代で人気でした。今日では、状態を持つ UI にはフレームワーク(Vue/React)が通常より良い選択です。しかしレガシーな jQuery サイトの拡張には、このパターンは依然有用でよく理解されています。

jquery
// stateful plugin using data + methods
(function ($) {
  $.fn.counter = function (method) {
    const methods = {
      init: function (options) {
        return this.each(function () {
          const $el = $(this)
          $el.data('count', options?.start || 0)
          $el.text($el.data('count'))
        })
      },
      increment: function () {
        return this.each(function () {
          const $el = $(this)
          const c = $el.data('count') + 1
          $el.data('count', c).text(c)
        })
      },
      reset: function () {
        return this.each(function () {
          $(this).data('count', 0).text(0)
        })
      }
    }

    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1))
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments)
    } else {
      $.error('Method ' + method + ' does not exist')
    }
  }
}(jQuery))

人気のプラグインの利用

jQuery UI が、ウィジェット(datepicker、accordion、autocomplete、dialog)とインタラクション(draggable、droppable、sortable)の公式の相棒ライブラリです。他の人気プラグイン:DataTables(機能豊富なテーブル)、Select2(拡張された select)、Slick(カルーセル)、Magnific Popup(モーダル)。プラグインの CSS と JS は jQuery の後に読み込みましょう。DOM ready で初期化します。多くのプラグインは、$('#x').plugin('method', args) のようなメソッド API と、plugin('option', name, val) 経由のオプション更新をサポートします。

jquery
<!-- jQuery UI (interactions, widgets, effects) -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<script>
// datepicker
$('#date').datepicker({ dateFormat: 'yy-mm-dd' })

// draggable / droppable / sortable
$('.item').draggable()
$('.list').sortable()

// dialog
$('<div>Hello</div>').dialog({ modal: true })
</script>

<!-- Other common plugins -->
<!-- DataTables: tables with sorting, search, pagination -->
<!-- Select2: enhanced <select> with search -->
<!-- Slick: carousel/slider -->
<!-- Magnific Popup: lightbox/modal -->

Widget Factory(jQuery UI)

jQuery UI の Widget Factory($.widget)が、状態を持ち継承に優しいプラグインを構築する構造化された方法です。_create(コンストラクタ)、_destroy(後始末)、_setOption、_on(自動後始末のイベント bind)、_trigger(カスタムイベント)が得られます。オプションはメソッド API 経由で公開されます:$el.widget('option', name, value)。カスタムイベントは widgetname + eventname として発火します。jQuery での複雑なステートフル UI には、widget factory が最も堅牢なパターンです — しかし新しいコードでは Vue/React への移行を検討しましょう。

jquery
// create a reusable widget with state + inheritance
$.widget('my.counter', {
  options: { start: 0 },

  _create: function () {
    this.count = this.options.start
    this._refresh()
    this._on(this.element, { click: 'increment' })
  },

  increment: function () {
    this.count++
    this._refresh()
    this._trigger('changed', null, { count: this.count })
  },

  _refresh: function () {
    this.element.text(this.count)
  },

  _destroy: function () {
    this.element.text('')
  }
})

// usage
$('#el').counter({ start: 5 })  // init
$('#el').counter('increment')   // call method
$('#el').on('counterchanged', function (e, data) {
  console.log('count is', data.count)
})
$('#el').counter('destroy')     // cleanup

プラグインのベストプラクティス

プラグインのベストプラクティス:(1) チェーン可能性のため必ず this を返す。(2) $ の安全のため IIFE で包む。(3) .each() を使い、マルチ要素の選択でも動くようにする。(4) イベントに名前空間を付け(click.myplugin)、ユーザーが他に影響せず unbind できるようにする。(5) オプションを $.extend でマージし、デフォルトを公開し、ユーザーがグローバルに上書きできるようにする。(6) destroy で後始末する(イベント、データ、DOM の変更)。(7) 衝突を避けるためプラグイン名に名前空間を付ける。(8) 柔軟性のため公開メソッドとデフォルトを公開する。

jquery
// 1. always return this for chainability
$.fn.green = function () { return this.css('color', 'green') }

// 2. use IIFE for $ safety
(function ($) { /* plugin */ })(jQuery)

// 3. iterate with .each() for multi-element support
$.fn.x = function () { return this.each(function () { /* per element */ }) }

// 4. namespace events so users can unbind cleanly
this._on(this.element, { 'click.myplugin': 'handler' })

// 5. accept options via $.extend
const opts = $.extend({}, $.fn.x.defaults, options)
$.fn.x.defaults = { color: 'red' }

// 6. clean up on destroy (events, data, DOM)
// 7. namespace your plugin name to avoid collisions
// 8. provide public methods + defaults accessible for override
11

属性とプロパティ

属性の getter と setter

.attr() が HTML の属性(マークアップの値、常に文字列)を読み書きします。.prop() が DOM のプロパティを読み書きします(現在の状態 — 例えば、checkbox の checked プロパティは、ユーザー操作後には checked 属性と異なることがあります)。真偽値の属性(checked、disabled、selected)には .prop() を、他(href、src、alt、data-*)には .attr() を使いましょう。.data() は data-* を読みますが、値を型を保ったまま内部キャッシュへ保存します — DOM 属性自体の更新には .attr('data-*') を使いましょう。

jquery
// .attr: HTML attribute (what's in the markup)
$('img').attr('src')              // get
$('img').attr('src', 'new.jpg')   // set
$('img').attr({                   // set multiple
  src: 'new.jpg',
  alt: 'Photo',
  width: 200
})

// .removeAttr: remove attribute entirely
$('img').removeAttr('alt')

// .prop: DOM property (current state, may differ from attr)
$('input').prop('checked')        // true/false (current state)
$('input').prop('checked', true)  // check it
$('input').prop('disabled', true)

// data-* attributes
$('div').attr('data-id', 42)      // sets the attribute (string)
$('div').data('id', 42)           // stores in cache (typed)

Data 属性

.data(name) が data-* 属性を自動型変換付きで読みます(数値、真偽値、JSON)。.data(name, value) 経由の設定は内部キャッシュへ書き、属性ではありません — そのため .attr('data-name') は依然元の値を返します。実際の DOM 属性(CSS セレクタやサーバー側の読み取りのため)を更新するには、.attr('data-name', value) を使いましょう。この区別を混同するとバグになります。キャッシュの消去は .removeData です。camelCase の名前:data-foo-bar が .data('fooBar') になります。

jquery
<!-- HTML -->
<div class="box" data-id="42" data-name="alice" data-active="true" data-config='{"x":1}'></div>

<script>
// .data() reads data-* with auto type conversion
$('.box').data('id')       // 42 (number, not string)
$('.box').data('name')     // 'alice'
$('.box').data('active')   // true (boolean)
$('.box').data('config')   // { x: 1 } (parsed JSON)

// set data (stored in cache, NOT the attribute)
$('.box').data('id', 99)
$('.box').data('id')       // 99
$('.box').attr('data-id')  // still '42' (attribute unchanged)

// to update the attribute itself, use .attr
$('.box').attr('data-id', 99)

// remove data
$('.box').removeData('id')
</script>

フォームのプロパティ

フォームの状態には .prop()(真偽値の DOM プロパティ)を使いましょう — .prop('checked') は現在の状態を反映し、.attr('checked') は初期の HTML 属性を返します(ユーザー操作では更新されない)。フォーム値の取得・設定は .val() が一律に行います。radio では :checked のものを見つけ .val() を読みましょう。マルチ select では .val() が配列を返します。きれいな真偽値チェックは .is(':checked') です。これらの区別が、フォームのバリデーションとシリアライズで重要になります。

jquery
// checkbox state
$('input[type=checkbox]').prop('checked')     // true/false
$('input[type=checkbox]').prop('checked', true)
$('input[type=checkbox]').is(':checked')      // boolean

// disabled / readonly
$('input').prop('disabled', true)
$('input').prop('readOnly', true)  // note: camelCase

// select value
$('select').val()                  // selected value
$('select').val('option2')         // set selected
$('select option:selected').text() // selected text

// multiple select
$('select[multiple]').val()        // ['a', 'b'] array

// radio: value of checked
$('input[name=gender]:checked').val()

//.prop vs .attr for checkboxes:
// .prop('checked') = current state (changes when clicked)
// .attr('checked') = initial HTML value (doesn't change)

クラスと属性の使い分け

要素の状態を CSS と JS へ公開する 3 つの方法:クラス(広く知られ、.hasClass)、data-* 属性(クエリ可能、値を運ぶ)、ARIA 属性(スクリーンリーダーがアクセス可能)。視覚的状態にはクラスが最も単純です。多値の状態(data-state='loading|success|error')には data-* がきれいです。アクセシビリティには aria-* を使いましょう(aria-pressed、aria-expanded、aria-busy)— 視覚状態としばしば重なるため、ペアにしましょう。モダンなフレームワークなら楽ですが、jQuery ではどれを選ぶか意図的に考えましょう。

jquery
// adding behavior tags via class
$('.btn').addClass('loading')
// CSS: .btn.loading { opacity: 0.5; pointer-events: none; }

// via data attribute (cleaner for state)
$('.btn').attr('data-state', 'loading')
// CSS: .btn[data-state="loading"] { ... }

// via aria (accessible)
$('.btn').attr('aria-busy', 'true')

// choosing:
// - class: many CSS hooks, well-known
// - data-*: cleaner for state values, queryable
// - aria-*: exposes state to screen readers

// toggling example
$('.btn').on('click', function () {
  const $b = $(this)
  $b.attr('aria-pressed', $b.attr('aria-pressed') !== 'true')
})

値(フォームフィールド)

.val() がフォーム値の汎用の getter/setter です — テキスト入力、textarea、select、そして(radio/checkbox では)チェックされたものの値。.serialize() が URL エンコードされた文字列を作り、.serializeArray() が {name, value} の配列を与えます — 素のオブジェクトへの変換は .serializeArray().reduce((o, p) => (o[p.name] = p.value, o), {}) です。フォームのリセットには、生の DOM 要素でネイティブの .reset() メソッドを呼びましょう(jQuery には .reset() メソッドがありません)。

jquery
// text input
$('input[type=text]').val()              // get current value
$('input[type=text]').val('new value')   // set

// textarea
$('textarea').val()

// select
$('select').val()                        // selected value
$('select').val('opt2')                  // set
$('select').val(['a', 'b'])              // multi-select set

// checkbox (use prop for state)
$('input[type=checkbox]').prop('checked')

// radio
$('input[type=radio][name=g]:checked').val()

// serialize whole form
$('form').serialize()                    // 'name=Alice&age=30'
$('form').serializeArray()               // [{name, value}]

// reset form
$('form')[0].reset()
12

寸法と位置

幅と高さのメソッド

幅/高さのメソッドは数値(px)を返します。単位付きの文字列を返す .css('width') とは違います。.width() = コンテンツボックス(CSS の幅)。.innerWidth() = コンテンツ + パディング。.outerWidth() = コンテンツ + パディング + 罫線。.outerWidth(true) はマージンを含みます。window/document では、$(window).width() がビューポート(見える領域)で、$(document).height() がフルページの高さです(スクロール時にはビューポートより大きくなり得ます)。setter は数値(px)か文字列('50%'、'10em')を受け付けます。

jquery
// content box (no padding, border, margin)
$('.box').width()       // 200 (number, px)
$('.box').width(300)    // set to 300px

// inner (content + padding)
$('.box').innerWidth()
$('.box').innerHeight()

// outer (content + padding + border)
$('.box').outerWidth()
$('.box').outerHeight()

// outer + margin
$('.box').outerWidth(true)
$('.box').outerHeight(true)

// window & document
$(window).width()       // viewport width
$(window).height()      // viewport height
$(document).height()    // document height (may exceed viewport)

Position と Offset の違い

.offset() は文書基準です(絶対座標 — ドラッグ・ドロップ、マウス位置のツールチップに有用)。.position() はオフセットの親基準です(position:relative/absolute/fixed を持つ最も近い祖先)— コンテナ内での再配置に有用です。.offsetParent() がその祖先を見つけます。.scrollTop()/.scrollLeft() がスクロール位置を取得・設定します — $(window).scrollTop() がページのスクロールです。offset(文書)と position(親)の区別が、正しい位置計算のために決定的に重要です。

jquery
// .offset(): relative to document (top-left of page)
const o = $('.box').offset()
console.log(o.left, o.top)         // e.g., 100, 200
$('.box').offset({ top: 0, left: 0 })  // move to top-left of page

// .position(): relative to offset parent
const p = $('.box').position()
console.log(p.left, p.top)         // position within parent

// .scrollTop() / .scrollLeft()
$(window).scrollTop()              // how far page is scrolled down
$(window).scrollTop(0)             // scroll to top
$('.container').scrollTop(100)     // scroll inner container

// .offsetParent(): nearest positioned ancestor
$('.box').offsetParent()           // the element .position() is relative to

レスポンシブレイアウトのヘルパー

resize はドラッグ中に何度も発火します — パフォーマンス問題を避けるため setTimeout で debounce しましょう。body へクラスを加えれば(mobile/desktop)、CSS が body.mobile .nav { ... } で応答できます。モダンなレスポンシブコードでは、スタイリングには CSS メディアクエリ、JS には window.matchMedia() を推奨します — より高性能で CSS のブレークポイントと一致します。jQuery の resize のアプローチはレガシーコードには構いませんが、CSS + matchMedia がモダンな標準です。

jquery
// check viewport width on resize
$(window).on('resize', function () {
  const w = $(window).width()
  if (w < 768) {
    $('body').addClass('mobile').removeClass('desktop')
  } else {
    $('body').addClass('desktop').removeClass('mobile')
  }
}).resize()  // trigger once to initialize

// debounced resize (avoid firing hundreds of times)
let timer
$(window).on('resize', function () {
  clearTimeout(timer)
  timer = setTimeout(function () {
    console.log('resize settled')
  }, 200)
})

// match media (preferred for responsive checks)
if (window.matchMedia('(max-width: 768px)').matches) {
  // mobile
}

要素の可視性の検出

:visible/:hidden は display、visibility、opacity、寸法を確認します — jQuery 3+ では visibility:hidden と opacity:0 を隠れたものとして扱います(古いバージョンでは見えるものとして扱っていました)。ビューポートの検出には、inViewport のヘルパーが要素の境界をスクロール位置と比較します。モダンなコードはこれに IntersectionObserver を使います — はるかに効率的で(計算はブラウザが行い、変化のときだけコールバック)、スクロールリスナーも不要です。jQuery のアプローチは機能しますが、スクロールイベントごとに発火します。

jquery
// :visible / :hidden pseudo-classes
$('.box').is(':visible')   // boolean
$('.box:visible').doSomething()

// note: visibility:hidden is now :hidden in jQuery 3+
// (display:none, opacity:0, width:0/height:0 are also :hidden)

// is element in viewport?
function inViewport($el) {
  const elTop = $el.offset().top
  const elBottom = elTop + $el.outerHeight()
  const docTop = $(window).scrollTop()
  const docBottom = docTop + $(window).height()
  return elBottom >= docTop && elTop <= docBottom
}

// scroll-triggered reveal
$(window).on('scroll', function () {
  $('.reveal').each(function () {
    if (inViewport($(this))) {
      $(this).addClass('shown')
    }
  })
})

スクロール位置とアニメーション

滑らかなスクロール:html と body の両方で scrollTop をアニメーションさせましょう(クロスブラウザ)。固定ナビのためにはヘッダーの高さを引き算します。無限スクロール:スクロール位置 + ビューポートの高さが文書の高さの N ピクセル以内になったら、より多くのコンテンツをロードします。パララックス:スクロール位置に基づき要素を translate します。スクロールハンドラは必ず throttle しましょう(1 秒に何十回も発火します)— _.throttle、タイマーベースの debounce、requestAnimationFrame を使いましょう。モダンな代替:スクロールには CSS の scroll-behavior:smooth、トリガーには IntersectionObserver。

jquery
// current scroll position
const scrollTop = $(window).scrollTop()

// smooth scroll to top
$('html, body').animate({ scrollTop: 0 }, 500)

// smooth scroll to element
function scrollTo($el, duration) {
  const top = $el.offset().top - 20  // 20px offset for fixed header
  $('html, body').animate({ scrollTop: top }, duration || 500)
}
scrollTo($('#section2'))

// infinite scroll: load more when near bottom
$(window).on('scroll', function () {
  if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
    loadMore()
  }
})

// parallax (simple)
$(window).on('scroll', function () {
  const y = $(window).scrollTop()
  $('.hero').css('transform', 'translateY(' + (y * 0.5) + 'px)')
})
13

Deferred と Promises

Deferred の作成

$.Deferred は jQuery の promise 実装です(ネイティブの Promise より古い)。作成したら、.resolve(value) か .reject(reason) で確定させましょう。.promise() が読み取り専用のビューを返します(利用者は確定できません)。レガシー API は、.then/.catch の代わりに .done/.fail/.always を使います。jQuery 3+ の Deferred は thenable であるため、await と Promise.resolve が機能します。新規コードにはネイティブの Promise を推奨します — Deferred は主に AJAX とレガシー API に関連します。

jquery
// create a Deferred (jQuery's promise source)
const deferred = $.Deferred()

// resolve or reject it later
setTimeout(function () {
  if (Math.random() > 0.5) {
    deferred.resolve('success data')
  } else {
    deferred.reject(new Error('failed'))
  }
}, 1000)

// get the promise (read-only view)
const promise = deferred.promise()

// consume it
promise
  .done(function (data) { console.log('done:', data) })
  .fail(function (err) { console.log('fail:', err) })
  .always(function () { console.log('settled') })

When(並行非同期)

$.when(deferreds...) が複数の Deferred/Promise の解決をすべて待ち、各結果の配列と共に .done を呼びます。どれかが拒否すれば、.fail が即座に発火します。これが並行非同期のパターンです(Promise.all のような)。コールバックは入力の deferred ごとに 1 配列を受け取ります(AJAX では [data, status, xhr] を含む)。モダンなコードでは、Promise.all + fetch の方がきれいで、解決済みの値を直接返します。$.when は jQuery が濃いコードベースでは依然有用です。

jquery
// run multiple async ops in parallel, wait for all
$.when(
  $.get('/api/users'),
  $.get('/api/posts'),
  $.get('/api/comments')
).done(function (usersResp, postsResp, commentsResp) {
  // each arg is [data, status, xhr]
  const users = usersResp[0]
  const posts = postsResp[0]
  console.log('all loaded:', users, posts)
}).fail(function (err) {
  console.error('one failed:', err)
})

// modern equivalent
Promise.all([
  fetch('/api/users').then(r => r.json()),
  fetch('/api/posts').then(r => r.json())
]).then(([users, posts]) => {
  console.log('all loaded:', users, posts)
})

.then() のチェーン

jQuery 3+ は .then を Promises/A+ の仕様に合わせました — (onFulfilled, onRejected) を受け取り、ネイティブの Promise.then と同様に新しい promise を返します。非同期操作のチェーンと値の変換ができます。.then から promise を返せば待ち、値を返せば下流へ渡ります。.catch も 3+ でサポートされています。jQuery 1.x/2.x では .then は非標準の挙動だったため、代わりに .pipe を使いましょう。可能なら 3+ へアップグレードし、きれいな非同期コードのため .then/.catch を使いましょう。

jquery
// jQuery 3+: .then follows Promises/A+ (like native then)
$.get('/api/users')
  .then(function (users) {
    // transform or chain another async
    return $.get('/api/users/' + users[0].id)
  })
  .then(function (userDetail) {
    console.log('detail:', userDetail)
    return userDetail.name  // pass value downstream
  })
  .then(function (name) {
    console.log('name:', name)
  })
  .catch(function (err) {
    console.error('any error in chain:', err)
  })

// in jQuery 1.x/2.x, .then had different semantics
// use .done/.pipe for old code; .then for new

AJAX の Promise インターフェース

すべての $.ajax 呼び出し(と $.get/$.post)が jqXHR オブジェクトを返します。これは promise 風(.done/.fail/.always をサポート)で、(jQuery 3+ では)thenable です(await と Promise.resolve が機能します)。複数の .done コールバックを付けられます — 成功時にすべて発火します。リクエストのキャンセルは .abort() です(ステータス 'abort' 付きの .fail をトリガー)。新規コードでは、await $.ajax(...) か Promise.resolve() で包み、ネイティブの Promise チェーンと async/await ときれいに統合しましょう。

jquery
// $.ajax returns a jqXHR (promise-like)
const req = $.ajax({ url: '/api/data', method: 'GET' })

// multiple callbacks on same request
req.done(function (data) { console.log('handler 1', data) })
req.done(function (data) { console.log('handler 2', data) })
req.fail(function (xhr, status, err) { console.error(err) })
req.always(function () { console.log('settled') })

// abort an in-flight request
req.abort()

// convert to native Promise (jQuery 3+)
Promise.resolve(req).then(function (data) {
  console.log('via native promise:', data)
})

// use with async/await (jQuery 3+)
async function getData() {
  try {
    const data = await $.ajax({ url: '/api/data' })
    console.log(data)
  } catch (err) {
    console.error(err)
  }
}

カスタムの Promise パイプライン

任意の非同期操作を Deferred で包めば promise が得られます:作成し、後に resolve/reject し、.promise() を返す。jQuery のコレクションも .promise() を公開します。これは要素上のキューに入ったすべてのアニメーションの完了で解決されるため、一連のアニメーション後にコードをトリガーするのに有用です。これが jQuery のアニメーションキューと promise ベースのコードを橋渡しし、アニメーションを await したり、AJAX や他の非同期作業ときれいにチェーンさせられます。

jquery
// wrap a callback-based API in a promise
function delay(ms) {
  const d = $.Deferred()
  setTimeout(function () { d.resolve() }, ms)
  return d.promise()
}

// use it
delay(500).then(function () { console.log('500ms passed') })

// animate then continue
$('.box').fadeOut(300).promise().done(function () {
  console.log('fade done')
})

// queue of animations on multiple elements
$('.box').each(function (i) {
  $(this).delay(i * 100).fadeIn().promise()
})

// when animations on a set are done
$('.box').fadeOut().promise().done(function () {
  console.log('all boxes faded')
})
14

フォーム

フォームのイベント

submit はフォーム送信で発火します — AJAX では必ず preventDefault しましょう。input は(テキストの)各キーストロークか値の変化で発火します — ライブバリデーションや入力しながらの検索に最適です。change はテキスト入力では blur で発火しますが、checkbox、radio、select では即座に発火します。focus/blur はフィールドのフォーカスで発火します。動的に追加されるフィールドのため、フォーム上のイベント委譲を使いましょう。'change' と 'input' の区別が重要です:'input' はライブで、'change' はユーザーが編集を終えたときです。

jquery
// submit event
$('form').on('submit', function (e) {
  e.preventDefault()  // stop page reload
  const data = $(this).serialize()
  $.post('/api/save', data)
})

// input event (fires on every keystroke/change)
$('input').on('input', function () {
  console.log('current value:', $(this).val())
})

// change event (fires on blur for text, immediately for checkbox/select)
$('select').on('change', function () {
  console.log('selected:', $(this).val())
})

// focus / blur
$('input').on('focus', function () { $(this).addClass('focused') })
$('input').on('blur', function () { $(this).removeClass('focused') })

// delegated (works for dynamically added fields)
$('form').on('input', '.field', function () { /* ... */ })

フォームデータのシリアライズ

.serialize() が AJAX データとして使える URL エンコードされた文字列を作ります。.serializeArray() が {name, value} の配列を与えます — reduce で素のオブジェクトへ変換しましょう。どちらもフォームの現在の状態を尊重します(checkbox はチェックされたときだけ含まれ、select は選択された option を使う)。checkbox の value は、value='something' を設定しない限りデフォルトで 'on' です。無効なフィールドは除外されます。これが、フルリロードなしで AJAX 送信のためのフォームデータを集める標準的な方法です。

jquery
<!-- form -->
<form id="f">
  <input name="name" value="Alice">
  <input name="email" value="[email protected]">
  <select name="role"><option value="admin" selected>Admin</option></select>
  <input type="checkbox" name="agree" checked>
</form>

<script>
// serialize: URL-encoded string
$('#f').serialize()
// 'name=Alice&email=a%40b.com&role=admin&agree=on'

// serializeArray: array of {name, value}
$('#f').serializeArray()
// [{ name: 'name', value: 'Alice' }, ...]

// convert to plain object
const obj = {}
$('#f').serializeArray().forEach(p => { obj[p.name] = p.value })
// { name: 'Alice', email: '[email protected]', role: 'admin', agree: 'on' }

// or one-liner reduce
const obj2 = $('#f').serializeArray().reduce((o, p) =>
  (o[p.name] = p.value, o), {})
</script>

フォームのバリデーション

手動のバリデーション:必須フィールドを反復し、.val() を確認し、CSS スタイリングのため 'invalid' クラスをトグルしましょう。メールの正規表現は基本的な整合性チェックです(完全な RFC 5322 の正規表現は過剰です)。複雑なフォームには、宣言的なルール(class='required email')と一貫したエラーメッセージを提供する jQuery Validation Plugin を使いましょう。UX のためのクライアント側バリデーションと、セキュリティのためのサーバー側バリデーションは必ず両方行いましょう — クライアント側はバイパスできます。HTML5 の属性(required、type='email'、pattern)がモダンな基準です。

jquery
// simple validation
function validate($form) {
  let valid = true
  $form.find('[data-required]').each(function () {
    const $f = $(this)
    if (!$f.val()) {
      $f.addClass('invalid')
      valid = false
    } else {
      $f.removeClass('invalid')
    }
  })
  $form.find('[type=email]').each(function () {
    if (!/^[^@]+@[^@]+\.[^@]+$/.test($(this).val())) {
      $(this).addClass('invalid')
      valid = false
    }
  })
  return valid
}

$('form').on('submit', function (e) {
  e.preventDefault()
  if (validate($(this))) {
    $.post('/api/save', $(this).serialize())
  }
})

動的なフォームフィールド

フォームフィールドの動的な追加・削除には、$() で要素を作り append しましょう。サーバーが配列を受け取るよう、配列風の名前(tags[])を使います。動的に追加された削除ボタンのクリックは、イベント委譲(on('click', '.remove', ...))で処理します。並べ替え可能なフィールド(上下ボタンやドラッグ・ドロップ付き)では、サーバーがきれいな順序を見るよう、各変更後に名前を付け直しましょう。このパターンは、タグ入力、動的な明細行、設定フォームでよくあります。

jquery
// add a new field
$('.add-field').on('click', function () {
  const $field = $('<input>', {
    type: 'text',
    name: 'tags[]',
    class: 'tag-input',
    placeholder: 'Tag'
  })
  $('#fields').append($field)
})

// remove a field
$('#fields').on('click', '.remove', function () {
  $(this).closest('.field-row').remove()
})

// array field names (tags[]) — server receives an array
// PHP/Rails auto-parse 'name[]' into arrays

// re-number fields after add/remove
function renumber() {
  $('#fields .field').each(function (i) {
    $(this).find('input').attr('name', 'item_' + i)
  })
}

AJAX によるフォーム送信

再利用可能な AJAX フォームハンドラ:フォームをシリアライズし、action URL へ POST し、成功/エラーを処理します。重複送信を防ぐため、リクエスト中は送信ボタンを無効化しましょう。他のコードが反応できるよう、カスタムイベント(ajax:success、ajax:error)をトリガーします。成功時にはフォームをリセットします。フィールド名をエラーメッセージへマッピングして、サーバーの検証エラーを表示しましょう。このパターンは、class='ajax' を加えるだけで任意のフォームを AJAX フォームへ変えます — プログレッシブエンハンスメントの一般的な拡張です。

jquery
// generic AJAX form submission
$('form.ajax').on('submit', function (e) {
  e.preventDefault()
  const $form = $(this)
  const data = $form.serialize()
  const url = $form.attr('action') || window.location.href
  const method = $form.attr('method') || 'POST'

  // show loading state
  $form.find('button').prop('disabled', true).addClass('loading')

  $.ajax({
    url: url,
    method: method,
    data: data,
    dataType: 'json'
  })
  .done(function (resp) {
    $form.trigger('ajax:success', [resp])
    $form[0].reset()
  })
  .fail(function (xhr) {
    $form.trigger('ajax:error', [xhr])
    const errors = xhr.responseJSON?.errors
    if (errors) showErrors($form, errors)
  })
  .always(function () {
    $form.find('button').prop('disabled', false).removeClass('loading')
  })
})
15

反復とループ

$.each と .each() の違い

$.each は、配列(index, value)かプレーンオブジェクト(key, value)を反復する汎用ユーティリティです。.each() は jQuery コレクション上のメソッドです — 'this' が生の DOM 要素です。どちらも中断には return false を、続行にはそれ以外を受け付けます。引数の順序が (index, value) で — Array.forEach の (value, index) と逆なのに注意しましょう。モダンなコードではネイティブの forEach/map/for...of が推奨です。.each() は、jQuery コレクションで作業し、要素を 'this' として必要なときに有用であり続けます。

jquery
// $.each: generic iterator (arrays AND objects)
$.each([10, 20, 30], function (index, value) {
  console.log(index, value)  // 0 10, 1 20, 2 30
})

$.each({ a: 1, b: 2 }, function (key, value) {
  console.log(key, value)  // 'a' 1, 'b' 2
})

// .each(): method on jQuery collections only
$('li').each(function (index, element) {
  // 'this' is the DOM element (= element)
  // wrap with $(this) for jQuery methods
  $(this).text(index + ': ' + $(this).text())
})

// breaking out
$('li').each(function (i) {
  if (i === 3) return false  // stop iteration
  // return true (or nothing) to continue
})

$.map と .map() の違い

$.map が配列/オブジェクトを新しい配列へ変換します(スキップには null を返し、配列を返すと平坦化されます)。引数の順序が (value, index) で — $.each と逆なのに注意しましょう。jQuery コレクション上の .map() は新しい jQuery コレクションを返します(素の配列への変換には .get() を呼ぶ)。.map() から null/undefined を返すとそのアイテムが除外されます。これらはネイティブの Array.map より古いです。モダンなコードはネイティブの map を使いますが、DOM コレクションからの値の抽出には jQuery の .map() が依然便利です。

jquery
// $.map: transform an array or object
const doubled = $.map([1, 2, 3], function (value, index) {
  return value * 2  // [2, 4, 6]
})

// returning null/undefined removes the item
const evens = $.map([1, 2, 3, 4], function (v) {
  return v % 2 === 0 ? v : null  // [2, 4]
})

// returning an array flattens it
const flat = $.map([1, 2], function (v) {
  return [v, v * 10]  // [1, 10, 2, 20]
})

// .map() on jQuery collections
const ids = $('li').map(function (index, el) {
  return $(el).data('id')  // jQuery collection of ids
}).get()  // .get() converts to plain array [1, 2, 3]

for/while でのループ

大きなコレクションでの生のパフォーマンスには、$items.eq(i)(jQuery ラップ)の代わりに $items[i](生の DOM 要素)を使うクラシックな for ループを使いましょう — 反復ごとに新しい jQuery オブジェクトの作成を避けられます。.length プロパティは直接機能します。for...of は jQuery コレクションで機能します(イテラブルです)。しかし、パフォーマンス問題を測定したのでなければ、読みやすさのため .each() を推奨します — 差は、数千の要素でない限りほとんど気づきません。

jquery
// classic for loop with .eq(i)
const $items = $('li')
for (let i = 0; i < $items.length; i++) {
  const $item = $items.eq(i)
  $item.text('Item ' + i)
}

// or use the raw DOM elements (faster, no jQuery wrapping)
for (let i = 0; i < $items.length; i++) {
  $items[i].textContent = 'Item ' + i  // raw DOM
}

// while loop
let i = 0
while (i < $items.length) {
  $($items[i]).addClass('item-' + i)
  i++
}

// for...of (modern, on the collection)
for (const el of $items) {
  $(el).addClass('processed')
}

反復中のフィルタ

よりきれいなコードのため、反復の前にフィルタしましょう — .each() の内側の条件分岐より、$('li').filter('.active').each(...) の方が慣用的です。サブセットを集めるには、一致する生の DOM 要素を配列へ push し、最後に $() で包みましょう。値の抽出には .map().get() が最もきれいなパターンです。ループ内での jQuery コレクションの構築は避けましょう(各 $() 呼び出しにオーバーヘッドがあります)— 生の要素を集め、一度だけ包みましょう。

jquery
// filter then iterate
$('li').filter('.active').each(function () {
  $(this).addClass('highlighted')
})

// iterate with conditional logic
$('li').each(function (i) {
  if (i % 2 === 0) {
    $(this).addClass('even')
  } else {
    $(this).addClass('odd')
  }
})

// collect matching items
const active = []
$('li').each(function () {
  if ($(this).hasClass('active')) {
    active.push(this)  // push raw DOM element
  }
})
const $active = $(active)  // wrap in jQuery

// or use .map().get()
const ids = $('li.active').map(function () {
  return $(this).data('id')
}).get()

ネストと複雑な反復

ネストした .each() がグリッド/行列を扱います。データから DOM を構築するには、document fragment へ append し、一度に挿入しましょう(アイテムごとの append よりはるかに速い — 各 append が reflow をトリガーします)。$(document.createDocumentFragment()) が jQuery ラップされた fragment を作ります。非常に大きなリストには、文字列連結 + .html()(最速)かテンプレートライブラリを検討しましょう。モダンなフレームワーク(Vue/React)はこれを宣言的に扱いますが、fragment のパターンは有用な jQuery の最適化であり続けます。

jquery
// nested iteration over rows and cells
$('table tr').each(function (rowIdx, row) {
  $(row).find('td').each(function (colIdx, cell) {
    $(cell).text('R' + rowIdx + 'C' + colIdx)
  })
})

// iterate over a JSON response and build DOM
$.get('/api/users').done(function (users) {
  const $list = $('#users')
  $.each(users, function (i, user) {
    $list.append(
      $('<li>').text(user.name).data('id', user.id)
    )
  })
})

// build with a document fragment (faster)
const $frag = $(document.createDocumentFragment())
$.each(users, function (i, user) {
  $frag.append('<li>' + user.name + '</li>')
})
$('#users').append($frag)  // one DOM update
16

データの保存とキャッシュ

$.data と .data() の違い

$.data(el, key, val) が生の DOM 要素上の低レベル関数で、.data() が jQuery コレクション上の便利なメソッドです。どちらも値を内部キャッシュ(DOM 内ではない)へ保存するため、属性アクセスより速いです。.data() は data-* 属性も型変換付きで(数値、真偽値、JSON)自動読み込みします。.data(key, val) 経由の設定は data-* 属性を更新しません — それには .attr('data-key', val) を使いましょう。消去には $.removeData(el, key) か .removeData(key) を使います。

jquery
// $.data: low-level, on raw DOM element
const el = document.getElementById('box')
$.data(el, 'count', 1)
$.data(el, 'count')       // 1
$.data(el, 'count', 2)
$.data(el, 'count')       // 2
$.removeData(el, 'count')

// .data(): method on jQuery collection (more common)
$('.box').data('count', 1)
$('.box').data('count')   // 1
$('.box').removeData('count')

// auto-reads data-* attributes (with type conversion)
// <div data-id="42" data-active="true"></div>
$('.box').data('id')      // 42 (number)
$('.box').data('active')  // true (boolean)

要素ごとの状態の保存

要素ごとの状態が .data() の決定的な機能です — DOM を汚染せずに、各要素に紐付いた設定、カウンタ、フラグ、オブジェクトを保存できます。引数なしの .data() 呼び出しが、保存されたすべてのデータをオブジェクトとして返します。オブジェクトを保存し書き換えると、保存された参照が書き換わることに注意しましょう(再設定は不要)。内部キャッシュは、.remove() で要素が取り除かれると自動的に片付けられ、メモリリークが防がれます — しかし生の DOM メソッド(parentNode.removeChild)で取り除いた場合は防がれません。

jquery
// store per-element state on plugin init
$('.counter').each(function () {
  $(this).data('count', 0)
})

// increment on click
$('.counter').on('click', function () {
  const $el = $(this)
  const c = $el.data('count') + 1
  $el.data('count', c)
  $el.text('Count: ' + c)
})

// retrieve all data
const all = $('.counter').data()  // { count: 5, ... }

// store objects
$('.box').data('config', { color: 'red', size: 10 })
$('.box').data('config').color = 'blue'  // mutates the stored object
$('.box').data('config').color  // 'blue'

選択のキャッシュ

jQuery 選択のキャッシュで、DOM の再クエリを避けられます — ループや頻繁なハンドラでの大きなパフォーマンス向上です。慣例:キャッシュされた jQuery オブジェクトには $ 接頭辞($boxes、$nav)を付け、生の DOM 要素と区別しましょう。注意:DOM が変わると(一致する要素を追加・削除すると)、キャッシュされた選択は古くなります。動的コンテンツの挿入後は再クエリしましょう。イベントハンドラでは、ハンドラの外(同じスコープ)でのキャッシュにより、イベントごとの再クエリを避けられます。

jquery
// BAD: re-querying the DOM on every use
function update() {
  $('.box').text('updated')     // queries every call
  $('.box').addClass('done')    // queries again
}

// GOOD: cache the selection
const $boxes = $('.box')        // query once
function update() {
  $boxes.text('updated')
  $boxes.addClass('done')
}

// re-query when content changes
$('#container').load('/partial', function () {
  // $boxes is stale — re-query
  const $newBoxes = $('.box')
})

// convention: prefix cached jQuery objects with $
const $nav = $('#nav')
const $items = $('.item')

HTML5 の data-* 属性

data-* 属性により、設定を HTML へ宣言的に埋め込めます — プログレッシブエンハンスメントに最適です(サーバーが設定を描画し、JS が読む)。.data() は型変換付きで読み(数値、真偽値、JSON オブジェクト)、.attr() は生の文字列を読みます。複数単語の名前は、HTML では kebab-case(data-foo-bar)、JS では camelCase(.data('fooBar'))です。JSON の値には、(ダブルクォートを使う JSON を)HTML ではシングルクォートで囲みましょう。.attr() 経由の data-* の更新は DOM へ永続化し、.data() はキャッシュだけに書きます。

jquery
<!-- declarative config in HTML -->
<div class="widget"
     data-id="42"
     data-mode="advanced"
     data-config='{"timeout":5000,"retries":3}'
     data-enabled="true">
  Widget
</div>

<script>
// .data() reads with type conversion
const $w = $('.widget')
$w.data('id')        // 42 (number)
$w.data('mode')      // 'advanced'
$w.data('config')    // { timeout: 5000, retries: 3 } (parsed JSON)
$w.data('enabled')   // true (boolean)

// .attr() reads raw strings
$w.attr('data-id')   // '42' (string)
$w.attr('data-config') // '{"timeout":5000,...}' (string)

// camelCase mapping: data-foo-bar -> .data('fooBar')
$('[data-foo-bar]').data('fooBar')
</script>

メモリと後始末

要素の削除には .remove() を使いましょう — 紐付いたデータとイベントが自動的に片付けられます。.detach() は DOM から取り除きますがデータ/イベントを保持します(再挿入用)。.empty() は子を取り除き、そのデータ/イベントも片付けます。子の消去に .html('') を使うのは NEVER です — そのデータ/イベントが片付かず、メモリリークになります。プラグインでは、イベントを unbind しデータを取り除く destroy メソッドを公開しましょう。生の DOM 削除より .remove() を使うべき大きな理由が、jQuery の自動後始末です。

jquery
// .remove() cleans up data and events
$('.box').remove()  // safe — data and events gone

// .detach() preserves data and events for re-insertion
const $box = $('.box').detach()
$('#elsewhere').append($box)  // events still fire

// .empty() removes children AND their data/events
$('.container').empty()  // children's data/events cleaned

// .html('') does NOT clean up children's data/events (leak!)
// use .empty() instead

// manual cleanup before removal
$('.box').off().removeData().remove()

// custom cleanup in a plugin
$.fn.myPlugin = function () {
  this.on('click.myplugin', handler)
  this.data('myplugin', { /* state */ })

  // expose destroy for manual cleanup
  // ... or use .on('remove') event (non-standard)
17

カスタムアニメーション

.animate() の基本

.animate() が、duration の間、数値の CSS プロパティを tween します。漸進的な変更には相対値('+=50'、'-=20')を使いましょう。プロパティ名は MUST で camelCase です(margin-left ではなく marginLeft)。特殊な値 'toggle'、'show'、'hide' がメソッドの対応物のように機能します。数値のデフォルトはピクセルです。色には jQuery Color プラグインが必要です — コアの jQuery は数値だけをアニメーションします。コールバックはアニメーション完了時に 1 回発火します(要素ごとなので、コレクションでは複数回発火し得ます)。

jquery
// animate numeric CSS properties
$('.box').animate({
  width: '500px',
  height: 200,         // number = px
  opacity: 0.5,
  marginLeft: '+=50',  // relative
  fontSize: '20px'     // camelCase for hyphenated props
}, 1000)  // duration in ms

// with callback
$('.box').animate({ left: 300 }, 1000, function () {
  console.log('done')
})

// 'slow' = 600, 'fast' = 200
$('.box').animate({ height: 'toggle' }, 'slow')

// special values: 'toggle', 'show', 'hide'
$('.box').animate({ width: 'toggle' })

イージングとオプション

イージングが速度曲線を制御します:'swing'(デフォルト、ゆっくり始まり終わる、中間は速い)と 'linear'(一定)です。jQuery UI や easing プラグインが 30 以上加えます(easeInOutCubic、easeOutBounce)。オプション形式できめ細かい制御が可能です:step はアニメーションの毎フレームで呼ばれ(他の要素の同期に有用)、queue:false で並行実行(デフォルトの true は逐次キュー)、specialEasing がプロパティごとのイージングを設定します。step は (now, fx) を受け取り、fx は fx.prop(プロパティ名)と fx.start/fx.end を持ちます。

jquery
// easing: 'swing' (default, ease-out) or 'linear'
$('.box').animate({ left: 300 }, 1000, 'linear')

// options object form
$('.box').animate({ left: 300 }, {
  duration: 1000,
  easing: 'swing',
  complete: function () { console.log('done') },
  step: function (now, fx) {
    console.log(fx.prop, now)  // called each frame
  },
  queue: true,         // default true (sequential)
  specialEasing: {
    width: 'linear',   // per-property easing
    height: 'swing'
  }
})

// jQuery UI adds more easings: easeInOutCubic, etc.
// or include jquery.easing plugin

アニメーションキュー

各要素には 'fx' キューがあります — 同じ要素上のアニメーションはデフォルトで逐次実行されます。並行実行には queue:false を使いましょう。.delay(ms) が一時停止を挿入します。.queue(fn) がキューへカスタム関数を挿入します — 続けるには next()(または dequeue())を呼びます。これで、アニメーションと任意のコード(AJAX、コールバック)をシーケンスで混ぜられます。キューの空化は .clearQueue() です(現在のアニメーションには影響しません)。キューの次のアイテムへの進行は .dequeue() です。

jquery
// animations queue per element (default)
$('.box')
  .animate({ width: 500 }, 500)  // runs first
  .animate({ height: 300 }, 500) // runs after
  .animate({ opacity: 0.5 }, 500) // runs after that

// total: 1500ms (sequential)

// run in parallel: queue: false
$('.box').animate({ width: 500 }, { duration: 500, queue: false })
$('.box').animate({ height: 300 }, { duration: 500, queue: false })
// both run simultaneously

// .delay(): pause in the queue
$('.box')
  .animate({ width: 500 }, 500)
  .delay(300)              // wait 300ms
  .animate({ height: 300 }, 500)

// .queue(): insert custom function into the queue
$('.box').animate({ width: 500 }, 500).queue(function (next) {
  console.log('between animations')
  next()  // must call to continue
})

色のアニメーション

コアの jQuery は色をアニメーションできません(非数値のため)。jQuery Color プラグイン(小さくスタンドアロン)か jQuery UI が色のアニメーション対応を加えます — backgroundColor、color、borderColor など。jQuery UI はクラスベースのアニメーションも可能にします:.addClass('foo', 500) が 500ms かけて新しいクラスのスタイルへ遷移します。モダンなサイトには、CSS トランジション(transition: background 0.3s)を推奨します — ハードウェア加速され JS も不要です。jQuery の色アニメーションはレガシー対応のためだけに使いましょう。

jquery
<!-- jQuery core does NOT animate colors -->
<!-- include jQuery Color plugin or jQuery UI -->
<script src="https://code.jquery.com/color/jquery.color-2.2.0.min.js"></script>

<script>
// now color animations work
$('.box').animate({
  backgroundColor: '#ff0000',
  color: '#ffffff',
  borderColor: '#000000'
}, 1000)

// jQuery UI also enables:
// - class animations: .toggleClass('active', 500)
// - more easing functions
// - color transitions on hover
$('.box').hover(function () {
  $(this).animate({ backgroundColor: '#eee' }, 300)
}, function () {
  $(this).animate({ backgroundColor: '#fff' }, 300)
})
</script>

停止とクリア

.stop() が現在のアニメーションを止めます。(clearQueue=true) 付きでは、キューも空にします。(jumpToEnd=true) 付きでは、現在のアニメーションを最終状態へ飛ばします。.finish() がキューに入ったすべてのアニメーションを即座に最終状態へ飛ばします。アニメーション中の要素に :animated セレクタが一致します。マウスが素早く出入りしたときの蓄積を防ぐため、ホバー駆動のアニメーションには必ず .stop(true) をペアにしましょう — なければ、アニメーションがキューに積まれ、マウスが去った後も長く再生され、カクついた挙動になります。

jquery
// .stop([clearQueue], [jumpToEnd])
$('.box').stop()              // stop current, stay at current state
$('.box').stop(true)          // also clear the queue
$('.box').stop(true, true)    // clear queue AND jump current to end
$('.box').stop(false, true)   // jump current to end, keep queue

// .finish(): jump ALL queued animations to end state
$('.box').finish()

// prevent hover animation buildup
$('.box').hover(function () {
  $(this).stop(true).animate({ width: 300 }, 200)
}, function () {
  $(this).stop(true).animate({ width: 100 }, 200)
})

// check if currently animating
if (!$(':animated').length) { /* nothing animating */ }
if ($('.box').is(':animated')) { /* still animating */ }
18

イベント委譲

なぜ委譲か

イベント委譲は親へ 1 つのハンドラを bind し、子のクリックがバブルしてトリガーします。利点:(1) N ではなく 1 つのハンドラ(メモリ)、(2) 動的に追加された要素で自動的に機能、(3) セットアップが速い(1 bind 対 N bind)。.on() の第 2 引数('li')がセレクタのフィルタです — ハンドラ内の 'this' はマッチした子であり、親ではありません。子が振る舞いを共有する任意のリスト、テーブル、コンテナに委譲を使いましょう。唯一のコスト:イベントごとのわずかなオーバーヘッド(セレクタの確認)で、無視できます。

jquery
// ANTI-PATTERN: bind to each <li> directly
$('li').on('click', function () {
  $(this).toggleClass('done')
})
// - 1 handler PER <li> (100 items = 100 handlers)
// - NEW <li> added later DON'T get the handler
// - high memory, slow setup

// PATTERN: delegate to parent
$('ul').on('click', 'li', function (e) {
  $(this).toggleClass('done')
})
// - 1 handler total
// - works for future <li>
// - low memory, fast setup
// - 'this' is the <li> (not the <ul>)

委譲の実践

この todo リストのパターンが委譲の力を示します:#tasks 上の 2 つの委譲ハンドラが、現在と将来のすべてのアイテムの、削除ボタンとアイテムのトグルを処理します。新しい <li> の追加には再 bind が不要です。削除ボタンの e.stopPropagation() が、li のクリックも発火するのを防ぎます(削除中に .done がトグルしてしまう)。クリックされたボタンから囲む <li> を見つけるのが .closest('li') です。このパターンが、フレームワーク以前の jQuery SPA の基礎でした — そしてウィジェット風 UI では今も有用です。

jquery
<!-- dynamic list -->
<ul id="tasks">
  <li>Task 1 <button class="delete">×</button></li>
</ul>

<script>
// ONE delegated handler handles all current AND future items
$('#tasks').on('click', '.delete', function (e) {
  e.stopPropagation()
  $(this).closest('li').remove()
})

$('#tasks').on('click', 'li', function () {
  $(this).toggleClass('done')
})

// adding new items works without re-binding
$('.add').on('click', function () {
  $('#tasks').append('<li>New task <button class="delete">×</button></li>')
})
</script>

委譲と直接 bind の比較

直接 bind はハンドラをマッチした要素へ付け、委譲 bind は親へ付けセレクタでフィルタします。ハンドラ内の重要な違い:直接では、e.currentTarget === this === 要素です。委譲では、e.currentTarget が親(ハンドラが bind された場所)で、this がマッチした子(セレクタの一致)であり、e.target が実際にクリックされた要素(マッチした子の子孫かもしれない)です。委譲ハンドラで親へアクセスするには e.delegateTarget を使いましょう。

jquery
// DIRECT: bind directly to element
// - element must exist at bind time
// - handler attached to element itself
// - e.target === e.currentTarget === this
$('.btn').on('click', function (e) {
  console.log(e.currentTarget === this)  // true
})

// DELEGATED: bind to parent, filter by selector
// - works for future children
// - handler attached to parent
// - e.currentTarget = parent (the bound element)
// - this = child (matched selector)
// - e.target = actual clicked element (may be deeper child)
$('ul').on('click', 'li', function (e) {
  console.log(e.currentTarget)  // the <ul>
  console.log(this)              // the <li>
  console.log(e.target)          // clicked element (maybe <span> in li)
})

委譲ハンドラの unbind

他に影響せず特定のハンドラを unbind する最もきれいな方法が、名前空間(click.task)です。そのセレクタに一致する委譲ハンドラの除去は .off('click', 'li') です。すべての click ハンドラ(直接と委譲)の除去は .off('click') です。すべての除去は .off() です — 慎重に使うこと。特定のハンドラの除去には、元の関数参照を渡しましょう。プラグインでは、ユーザーが内部を知らずにきれいに unbind できるよう、必ずイベントに名前空間を付けましょう(click.myplugin)。

jquery
// delegate with namespace
$('ul').on('click.task', 'li', handler)

// remove just this delegated handler (by namespace)
$('ul').off('click.task')

// remove all delegated click handlers
$('ul').off('click')

// remove all delegated handlers with a specific selector
$('ul').off('click', 'li')

// remove ALL handlers (including delegated)
$('ul').off()

// remove with reference to the original handler
function handler() { /* ... */ }
$('ul').on('click', 'li', handler)
$('ul').off('click', 'li', handler)  // exact match

委譲の落とし穴

委譲は最も近い安定した祖先へスコープしましょう — すべてを document/body へ委譲してはいけません(すべてのイベントがバブルし、セレクタと照合され、遅くなります)。広すぎるセレクタ('div')は避けましょう。子の stopPropagation には注意しましょう:祖先上の委譲ハンドラの発火を防ぎます。子が伝播を止めると、親の委譲ハンドラは決して動きません。トレードオフ:委譲は柔軟ですが、イベントごとのわずかなオーバーヘッド(セレクタマッチング)を加えます — 通常無視できますが、巨大なページでは問題になります。

jquery
// PITFALL 1: delegated handler on a parent that's too high
$(document).on('click', '.btn', handler)
// works, but EVERY click bubbles to document and is checked
// (slow on large pages — scope to nearest stable parent)

// BETTER: scope to the nearest container that won't be replaced
$('#sidebar').on('click', '.btn', handler)

// PITFALL 2: selector that matches too broadly
$('body').on('click', 'div', handler)  // fires on every div click

// PITFALL 3: stopping propagation in a child breaks delegation
$('.btn').on('click', function (e) {
  e.stopPropagation()  // parent's delegated handler won't fire!
})

// PITFALL 4: delegated handlers don't fire if a parent
// stops propagation before reaching the delegate target
19

ベストプラクティス

パフォーマンスのヒント

重要なパフォーマンスのヒント:(1) 選択をキャッシュする。(2) クエリを .find() でコンテナへスコープする。(3) #id セレクタを推奨する(内部で getElementById を使う)。(4) * を避ける。(5) イベントを委譲する。(6) DOM の更新を fragment でバッチする — 各 append が reflow をトリガーするため、fragment を構築し一度 append する。(7) 重い操作の前に detach する(取り外された要素上の操作は reflow をトリガーしません)。1000 項目以上のリストでは、文字列連結 + .html() が最速ですが、fragment の方がきれいです。

jquery
// 1. cache selections
const $items = $('.items')  // query once

// 2. scope queries to a container
$('.item', $container)      // search within container
$container.find('.item')    // equivalent, slightly faster

// 3. use ID selectors when possible (fastest)
$('#header')                // getElementById

// 4. avoid universal selector
$('*').doSomething()        // SLOW

// 5. delegate events instead of binding many
$('ul').on('click', 'li', fn)  // 1 handler

// 6. batch DOM updates (use document fragment)
const $frag = $(document.createDocumentFragment())
for (let i = 0; i < 1000; i++) {
  $frag.append('<li>Item ' + i + '</li>')
}
$('ul').append($frag)  // one reflow, not 1000

// 7. detach before heavy manipulation
const $list = $('ul').detach()
// ... modify $list ...
$('#container').append($list)

DOM 挿入のパフォーマンス

DOM 挿入が最大のパフォーマンスのボトルネックです。各 .append() が reflow をトリガーします(ブラウザがレイアウトを再計算します)。一括挿入の方法:(1) HTML 文字列を組み立て .html() で設定する(単純なコンテンツには最速)。(2) document fragment を使い一度 append する(複雑な要素にはよりきれい)。(3) コンテナを detach し、修正し、再 attach する(修正中の生 DOM 上の reflow を避ける)。1000 項目以上では、文字列のアプローチがアイテムごとの .append() より大幅に速いです。

jquery
// SLOW: appending in a loop (reflow per iteration)
for (let i = 0; i < 1000; i++) {
  $('ul').append('<li>Item ' + i + '</li>')
}

// FASTER: build string, append once
let html = ''
for (let i = 0; i < 1000; i++) {
  html += '<li>Item ' + i + '</li>'
}
$('ul').html(html)

// FASTEST: detached node + fragment
const $list = $('ul').detach()
const $frag = $(document.createDocumentFragment())
for (let i = 0; i < 1000; i++) {
  $frag.append($('<li>').text('Item ' + i))
}
$list.append($frag).appendTo('#container')

// even faster: array.join
const html = new Array(1000).fill(0).map((_, i) =>
  '<li>Item ' + i + '</li>'
).join('')
$('ul').html(html)

モダンな jQuery パターン

モダンな jQuery(3.x)のパターン:.on()/.off() を使う(.bind/.live/.delegate のようなレガシーメソッドは削除か非推奨です)。success/error のコールバックより promise インターフェース(.done/.fail)を使いましょう。コードは IIFE か ES モジュールでスコープします — グローバルを汚染しません。スクリプトが body の末尾にあれば $(document).ready は省略します。.animate() より CSS トランジション/アニメーションを推奨しましょう(ハードウェア加速され滑らかです)。'use strict' を使いましょう。新しいプロジェクトでは、jQuery よりフレームワーク(Vue/React)が適切か検討しましょう。

jquery
// use .on() / .off() (not bind/unbind, live, delegate)
$('.btn').on('click', fn)

// use promises (.done/.fail) instead of success/error
$.get('/api').done(fn).fail(errFn)

// use IIFE or modules to scope code
(function ($) {
  'use strict'
  // private code
  $('.btn').on('click', fn)
}(jQuery))

// or ES modules
import $ from 'jquery'
$('.btn').on('click', fn)

// don't pollute global scope
// don't use $(document).ready if script is at end of body

// prefer CSS for animations (hardware-accelerated)
// .css({ transition: 'all 0.3s', transform: 'translateX(100px)' })

アクセシビリティ

アクセシビリティの要点:ARIA のロールと状態を加えましょう(role='dialog'、aria-modal、aria-expanded、aria-labelledby)。カスタムウィジェットはキーボードで操作可能にします — ボタンには Enter/Space を、メニューには矢印キーを、モーダルを閉じるには Esc を処理します。フォーカスの管理:モーダルを開くときフォーカスを内側へ移し、閉じるときトリガーへ返します。onclick 付きの div ではなく、セマンティックな要素(<button>、<a>、<nav>)を使いましょう。可視性:display:none(スクリーンリーダーが常に無視する)より、CSS クラス経由で隠す方を推奨します(無視されないことがあります)。

jquery
// add ARIA attributes for screen readers
$('.modal').attr({
  role: 'dialog',
  'aria-modal': true,
  'aria-labelledby': 'modal-title'
})

// toggle aria-expanded for collapsibles
$('.accordion .header').on('click', function () {
  const $h = $(this)
  const expanded = $h.attr('aria-expanded') !== 'true'
  $h.attr('aria-expanded', expanded)
  $h.next('.content').slideToggle()
})

// keyboard navigation
$('.menu-item').on('keydown', function (e) {
  if (e.which === 13 || e.which === 32) {  // Enter or Space
    $(this).trigger('click')
  }
})

// focus management for modals
$('.modal').on('shown', function () {
  $(this).find('input:first').focus()
})

// use button elements for actions (not <div onclick>)
$('<button>').text('Save').on('click', save).appendTo('body')

セキュリティ:XSS と HTML インジェクション

信頼できない文字列を .html() 経由で注入してはいけません — 埋め込まれた <script> タグとイベントハンドラが実行されます(XSS)。プレーンテキストには .text() を使いましょう(自動エスケープ)。HTML を含めなければならないときは、先にサニタイズしましょう(手動のエスケープか DOMPurify のようなライブラリ)。最も安全なパターン:$() で要素を構築し、動的コンテンツには .text() を使う — $('<li>').text(userInput) が自動的にエスケープします。.append('<div>' + data + '</div>') のようなパターンには特に注意しましょう — data がユーザー制御なら XSS の経路になります。

jquery
// DANGEROUS: injecting untrusted HTML
const userInput = '<script>alert("xss")</script>'
$('.box').html(userInput)        // EXECUTES the script!

// SAFE: escape with .text()
$('.box').text(userInput)        // displays as text, no execution

// SAFE: sanitize before injecting
function escapeHtml(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
}
$('.box').html(escapeHtml(userInput))

// SAFE: build elements with .text() for content
const $li = $('<li>').text(userInput)  // text is auto-escaped
$('ul').append($li)

// AVOID .html() with user input. Use .text() or DOMPurify.
// $('div').html('<p>' + data + '</p>')  // BAD if data is user input
20

よくあるパターン

モーダルダイアログ

モーダルのパターン:overlay + modal を作り、body へ append し(親のスタッキングコンテキストから逃れる)、フェードインさせます。モーダルではなく overlay のクリックで閉じます — 検出には e.target === this を使いましょう。Esc キーで閉じます。閉じるときは必ず後始末しましょう(DOM の削除、ハンドラの unbind)。本番では、アクセシビリティ(フォーカストラップ、ARIA、トリガーへのフォーカス返却)、アニメーション、iframe/ajax モーダルを扱うライブラリ(Magnific Popup、Bootstrap Modal)を検討しましょう。上のパターンが最小の手作り版です。

jquery
// simple modal pattern
function openModal(html) {
  const $overlay = $('<div class="modal-overlay"></div>')
  const $modal = $('<div class="modal"></div>').html(html)
  $overlay.append($modal).appendTo('body').hide().fadeIn(200)

  $overlay.on('click', function (e) {
    if (e.target === this) closeModal()  // click outside to close
  })

  $(document).on('keydown.modal', function (e) {
    if (e.which === 27) closeModal()  // Esc to close
  })
}

function closeModal() {
  $('.modal-overlay').fadeOut(200, function () { $(this).remove() })
  $(document).off('keydown.modal')
}

// usage
$('.open').on('click', function () {
  openModal('<p>Hello from modal!</p>')
})

Tabs

クラシックなタブのパターン:タブのリンクのクリックでそのタブがアクティブになります。リンクの href(#tab1)がコンテンツの id に対応します。リンクとコンテンツの両方のアクティブクラスが可視性を制御します(CSS:.tab-content:not(.active) { display: none })。ハンドラはイベント委譲を使い(動的に追加されたタブも処理します)、preventDefault が URL ハッシュの変化を止めます(omit すれば、ハッシュベースのタブへのディープリンクが可能になります)。アクセシビリティのため、role='tab'、aria-selected、キーボードの矢印ナビゲーションを加えましょう。

jquery
<!-- HTML -->
<div class="tabs">
  <ul class="tab-nav">
    <li><a href="#tab1" class="active">Tab 1</a></li>
    <li><a href="#tab2">Tab 2</a></li>
    <li><a href="#tab3">Tab 3</a></li>
  </ul>
  <div id="tab1" class="tab-content active">Content 1</div>
  <div id="tab2" class="tab-content">Content 2</div>
  <div id="tab3" class="tab-content">Content 3</div>
</div>

<script>
$('.tab-nav').on('click', 'a', function (e) {
  e.preventDefault()
  const $a = $(this)
  $a.addClass('active').parent().siblings().find('a').removeClass('active')
  $($a.attr('href')).addClass('active').siblings().removeClass('active')
})
</script>

Accordion

アコーディオンのパターン:ヘッダーのクリックでそのコンテンツがトグルします。単一開放のバリアントは、1 つが開くと他を閉じます(複数開放なら .not($h) のブロックを取り除く)。スクリーンリーダーへ状態を公開するには aria-expanded を使いましょう — CSS がそれに基づきスタイルできます(.acc-header[aria-expanded="true"] { ... })。コンテンツのアニメーションは slideToggle です。ヘッダーには <button> を使うと(デフォルトでキーボードで操作可能)、多くのアイテムでは、親上のイベント委譲により各ヘッダーの個別 bind が避けられます。

jquery
<!-- HTML -->
<div class="accordion">
  <div class="acc-item">
    <button class="acc-header" aria-expanded="false">Section 1</button>
    <div class="acc-content">Content 1</div>
  </div>
  <!-- more items -->
</div>

<script>
$('.accordion').on('click', '.acc-header', function () {
  const $h = $(this)
  const $c = $h.next('.acc-content')

  // close others (single-open accordion)
  $h.closest('.accordion')
    .find('.acc-header').not($h)
      .attr('aria-expanded', false)
      .next('.acc-content').slideUp()

  // toggle this one
  const isOpen = $h.attr('aria-expanded') === 'true'
  $h.attr('aria-expanded', !isOpen)
  $c.slideToggle()
})
</script>

無限スクロール

無限スクロール:ユーザーが末尾近くまでスクロールしたら検出し、より多くのアイテムを取得し、append します。同時ロードへの防御には(loading フラグ)、サーバーがもうアイテムを返さなければ、スクロールハンドラを unbind しましょう(もう試行しない)。パフォーマンスのため append は fragment 経由で行い、スクロールハンドラは throttle しましょう(1 秒に何度も発火します)— debounce/_.throttle か、(ここでのように)リクエストが進行中の間スキップする loading フラグの確認で。モダンな代替:末尾のセンチネル要素上の IntersectionObserver。

jquery
let loading = false
let page = 1

function loadMore() {
  if (loading) return
  loading = true
  $('.loader').show()

  $.get('/api/items', { page: page })
    .done(function (items) {
      if (items.length === 0) {
        // no more items — unbind the scroll handler
        $(window).off('scroll.inf')
        return
      }
      const $frag = $(document.createDocumentFragment())
      items.forEach(item => {
        $frag.append($('<li>').text(item.name))
      })
      $('ul.items').append($frag)
      page++
    })
    .always(function () {
      loading = false
      $('.loader').hide()
    })
}

// trigger when near bottom
$(window).on('scroll.inf', function () {
  if ($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
    loadMore()
  }
})

ライブ検索(Debounced)

ライブ検索:ユーザーがタイプするにつれ、サーバーをクエリし結果を表示します。debounce が不可欠です — なければ、すべてのキーストロークがリクエストを発火させます(素早いタイピング = 何十ものリクエスト)。debounce が、最後のキーストロークの N ms 後に発火を待ちます。300ms が良いデフォルトです。空のクエリは必ず処理しましょう(結果をクリア)。本番では、順序不正のレスポンスを避けるため、新しいリクエストが始まるとき進行中のリクエストをキャンセルしましょう(前の jqXHR 上で .abort())。モダンな代替:fetch との AbortController。

jquery
// debounce: wait until user pauses typing
function debounce(fn, wait) {
  let timer
  return function () {
    clearTimeout(timer)
    const args = arguments
    const ctx = this
    timer = setTimeout(() => fn.apply(ctx, args), wait)
  }
}

// live search
const $input = $('#search')
const $results = $('#results')

$input.on('input', debounce(function () {
  const q = $(this).val()
  if (!q) { $results.empty(); return }

  $.get('/api/search', { q: q })
    .done(function (items) {
      $results.empty()
      items.forEach(item => {
        $results.append($('<li>').text(item.name))
      })
    })
}, 300))  // wait 300ms after last keystroke

// without debounce, a search fires on every keystroke (too many requests)

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.