시작하기
jQuery 포함
빠르고 캐시된 로딩을 위해 CDN으로 jQuery를 포함하세요. 경량 버전(.min.js)은 프로덕션용이고, 비압축 버전은 디버깅용입니다. CDN에 접근할 수 없는 경우를 대비해 항상 로컬 폴백을 제공하세요. npm에서는 jQuery를 모듈로 임포트할 수 있습니다 — Webpack/Vite 같은 번들러에 유용. jQuery 3.7.x가 현재 라인이며, 구형 IE는 더 이상 지원되지 않습니다.
<!-- 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보다 먼저 발생합니다.
// 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 콜백에 $를 전달해 지역 별칭으로 쓸 수 있습니다.
// $ 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() 게터 같은)는 컬렉션이 아닌 값을 반환해 체인이 끊깁니다.
// 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무충돌 모드
$.noConflict()는 $의 제어권을 먼저 정의한 라이브러리에 돌려줍니다. 호출 후에는 전체 jQuery 이름을 쓰거나 jQuery를 커스텀 변수에 할당하세요. IIFE 패턴(function($){...})(jQuery)이 모듈 안에서 $를 지역 별칭으로 유지하면서 전역 $는 다른 라이브러리에 남겨두는 클래식 방법입니다 — WordPress와 레거시 환경에서 필수입니다.
// 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)선택자
기본 선택자
jQuery는 CSS 선택자를 씁니다(대부분 querySelectorAll과 호환). 큰 세 가지: 태그 이름, #id, .class. 쉼표가 선택자를 결합합니다(합집합). #id가 가장 빠릅니다(내부에서 getElementById 사용). 만능 *는 느립니다 — 큰 문서에서 피하세요. 선택 결과는 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(...)로 컨테이너에 스코프하세요.
// 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-* 속성에 유용합니다.
// 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, :text, :checked 등)는 jQuery 확장입니다 — CSS의 일부가 아니므로 querySelectorAll의 빠른 경로를 못 씁니다. 큰 폼의 성능에는 $(':text') 대신 $('input[type=text]')를 쓰세요. :checked와 :selected가 폼 상태 읽기에 필수입니다. 이들은 동적입니다 — 접근할 때마다 재평가됩니다.
// :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() 메서드를 권합니다.
// 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')이벤트
.on()으로 이벤트 바인딩
.on()이 현대적인 만능 이벤트 바인더입니다(.bind/.delegate/.live를 대체). 이벤트 이름(들)과 핸들러를 전달하세요. 핸들러 안의 'this'는 DOM 요소입니다(jQuery 래퍼가 아님 — 필요하면 $(this)로 감싸세요). 이벤트 네임스페이스(click.myapp)로 다른 핸들러에 영향 없이 특정 핸들러를 해제할 수 있습니다. 여러 이벤트가 하나의 핸들러를 공유하거나(공백 구분) 별개 핸들러를 가질 수 있습니다(객체 형식).
// 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이벤트 위임
이벤트 위임은 부모에 하나의 핸들러를 바인딩해 버블링으로 자식의 이벤트를 받습니다. .on()의 두 번째 선택자('li')가 어떤 자식이 핸들러를 트리거할지 필터합니다. 이점: N개 대신 하나의 핸들러, 동적으로 추가된 요소 자동 지원, 낮은 메모리. 긴 목록이나 SPA에 필수입니다. 'this'는 부모가 아니라 매칭된 자식(li)입니다. 부모에 접근하려면 e.delegateTarget을 쓰세요.
// 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()의 선택적 두 번째 인수로 핸들러에 데이터를 전달하세요.
$('.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 등)는 함수와 함께 호출되면 핸들러를 바인딩하고, 없이 호출되면 이벤트를 트리거합니다. .hover(enter, leave)는 mouseenter+mouseleave의 편의 메서드입니다. .on('event', fn)과 동등하지만 더 짧습니다. 일부 축약(.load, .error)은 jQuery 3에서 제거됐습니다 — 대신 .on('load', ...)를 쓰세요. 새 코드에는 .on()을 권합니다 — 더 명시적이고 위임을 지원합니다.
// 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)트리거 & 일회성 이벤트
.trigger('event')는 핸들러와 네이티브 동작(예: 내비게이션)을 모두 발생시킵니다; .triggerHandler()는 jQuery에 바인딩된 핸들러만 발생시키고 핸들러의 반환 값을 돌려줍니다(체이닝 불가). .one()은 첫 호출 후 자동 해제되는 핸들러를 바인딩합니다 — 첫 클릭 힌트, 일회성 셋업에 완벽합니다. 커스텀 이벤트로 컴포넌트가 통신합니다: $(document).trigger('myapp:ready')와 리스너가 .on('myapp:ready', fn)으로 구독합니다.
// 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')DOM 조작
콘텐츠 읽기 & 쓰기
.html()은 HTML 마크업을 다룹니다(innerHTML과 같음) — 태그가 파싱됩니다. .text()는 평문용입니다 — 태그가 이스케이프되어 그대로 표시됩니다(사용자 입력에 XSS로부터 더 안전). .val()은 폼 컨트롤(input, select, textarea)용입니다. 셋 모두 인수 없이 호출하면 게터(첫 요소의 값 반환), 인수와 함께 호출하면 세터(모든 매칭 요소에 적용)입니다. 세터는 콜백을 받습니다 (index, oldValue) => newValue.
// .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)은 주어와 목적지를 뒤집습니다 — 새 요소에서 체이닝할 때 유용. 위임으로 바인딩된 이벤트 핸들러는 새로 삽입된 요소에도 상속되지만, 삽입 전에 직접 바인딩한 것은 상속되지 않습니다.
// 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()은 부모를 제거하고 요소를 위로 올립니다. 항상 .remove()나 .detach()를 쓰세요 — 부모에 그냥 .html('')을 쓰지 마세요. 자식의 데이터/이벤트가 새어 나옵니다.
// 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()은 전체 집합을 한 그룹으로 감싸며, .wrapInner()는 내용을(요소 자체가 아님) 감쌉니다. .clone()은 깊은 복사를 만듭니다 — true를 전달하면 이벤트 핸들러와 데이터도 복제합니다(기본 false, 사본에서 핸들러가 발화하지 않음). .unwrap()은 직속 부모를 제거합니다. HTML 문자열을 다시 쓰지 않고 마크업을 재구성하는 데 강력합니다.
// 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'는 raw DOM 요소입니다; 중단하려면 false를 반환하고 계속하려면 다른 값을 반환하세요. .map()은 새 jQuery 컬렉션으로 변환합니다; 일반 배열로 바꾸려면 .get()을 호출하세요. .filter()는 선택자나 콜백으로 좁히고, .not()은 그 반대입니다. .is()는 불리언을 반환합니다(매칭되는 요소가 있는가?) — 조건문에 유용. .eq(i)와 for 루프는 피하고, 관용적인 jQuery에는 .each()나 .map()을 쓰세요.
// .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 */ }CSS 조작
CSS 속성 읽기 & 쓰기
.css()는 계산된 스타일을 얻거나(항상 해석된 값, CSS 규칙에서도) 인라인 스타일을 설정합니다. 게터에는 단일 프로퍼티 이름을 전달합니다(문자열 반환). 세터에는 (prop, value)나 prop:value 쌍의 객체를 전달하세요. 프로퍼티 이름은 camelCase나 kebab-case입니다(후자는 따옴표 필요). 숫자 값은 대부분의 프로퍼티에서 픽셀이 기본입니다. 레이아웃에는 .css()를 피하세요 — 유지보수성을 위해 클래스와 스타일시트를 쓰세요.
// 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'
})클래스 조작
클래스 메서드가 요소 스타일링의 선호 방법입니다 — 표현을 JS가 아닌 CSS에 유지합니다. .addClass, .removeClass, .toggleClass는 공백으로 구분된 클래스 목록을 받습니다. .toggleClass(name, bool)는 불리언에 따라 추가/제거합니다 — 상태 기반 UI에 유용. .hasClass(name)는 불리언을 반환합니다(첫 요소만 검사). 성능상, 단순하지 않은 스타일링에는 클래스가 .css()보다 훨씬 빠릅니다 — 변경을 배치하고 브라우저가 최적화하게 하기 때문입니다.
// 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() = 콘텐츠 박스(padding/border 제외). .innerWidth()/.innerHeight() = 콘텐츠 + padding. .outerWidth()/.outerHeight() = 콘텐츠 + padding + border. .outerWidth(true)는 margin 포함. 세터는 숫자(px)나 문자열을 받습니다. window/document에는 뷰포트에 $(window), 전체 페이지에 $(document)를 쓰세요. 이들은 숫자를 반환합니다(.css('width') 같은 문자열이 아님) — 계산에 편리합니다.
// 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위치 & 오프셋
.offset()은 문서 기준 {top, left}를 반환합니다(절대 위치나 드래그-드롭에 유용). .position()은 오프셋 부모(position: relative/absolute/fixed를 가진 가장 가까운 조상) 기준 좌표를 반환합니다. .scrollTop()/.scrollLeft()가 스크롤 위치를 읽거나 설정합니다 — $(window).scrollTop(0)이 맨 위로 스크롤합니다. .offsetParent()가 positioned 조상을 찾습니다. 애니메이션, 드래그-드롭, 무한 스크롤에 필수입니다.
// .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()스크롤 & 좌표
스크롤 처리는 스티키 내비, 무한 스크롤, 스크롤 트리거 애니메이션에서 흔합니다. $('html, body').animate({scrollTop: n})이 부드럽게 스크롤합니다. 성능을 위해 스크롤 핸들러를 스로틀하세요(스크롤당 여러 번 발생). isVisible 헬퍼가 요소가 뷰포트 안에 있는지 검사합니다 — 이미지 지연 로딩이나 애니메이션 트리거에 유용. 현대의 IntersectionObserver가 가시성 감지에 더 효율적입니다; 새 프로젝트에서는 고려하세요.
// 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)
}AJAX
$.ajax (완전 제어)
$.ajax가 저수준 완전 제어 메서드입니다. method/http 동사, data(GET은 쿼리로, POST는 본문으로 전송), dataType이 기대 응답을 힌트합니다(자동 파싱). success/error/complete는 레거시 콜백 훅입니다. beforeSend로 xhr을 수정합니다(헤더 추가). timeout이 N ms 뒤 중단합니다. 현대 코드에는 success/error 콜백 대신 fetch()나 .done()/.fail() 프로미스를 쓰는 $.ajax를 권합니다.
$.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 요청의 축약형입니다. 프로미스류 인터페이스(.done/.fail/.always)가 success/error 콜백보다 깔끔하고 — 여러 .done 핸들러의 체이닝도 지원합니다. JSON 요청 본문에는 contentType: 'application/json' 설정과 JSON.stringify가 모두 필요합니다(jQuery는 객체를 JSON으로 자동 stringify하지 않음). 참고: jQuery의 프로미스는 Deferred이지 네이티브 Promise가 아니지만 대부분의 경우 비슷하게 동작합니다.
// 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 업데이트가 권장됩니다.
<!-- 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(프로미스류) 객체를 반환합니다. 오늘날 교차 도메인 요청에는 서버가 CORS 헤더를 보내도록 하세요; JSONP는 CORS 이전의 우회법으로 보안상 주의점이 있습니다.
// 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 토큰을 포함하세요.
// 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}, ...]효과 & 애니메이션
기본 표시/숨기기
.show()/.hide()/.toggle()이 display를 바꿉니다. 인수 없이는 즉시 표시/숨김입니다. 지속 시간을 주면 width/height/opacity를 애니메이션합니다. 'slow' = 600ms, 'fast' = 200ms, 또는 ms 숫자. 콜백은 애니메이션 완료 시 발생합니다. jQuery 애니메이션은 기본적으로 requestAnimationFrame을 씁니다(끊김 없음). 참고: .hide()는 display:none을 설정하고, .show()는 원래 display 값을 복원합니다. 더 세밀한 제어에는 .animate()를 직접 쓰세요.
// 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에는 표시/숨기기보다 페이드가 더 부드럽습니다.
// 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슬라이드
슬라이드는 height(와 display)를 애니메이션합니다. .slideDown이 요소를 드러내고(display:none에서 자연 높이로), .slideUp이 숨기고(0으로 접어 display:none), .slideToggle이 상태를 뒤집습니다. 아코디언, 드롭다운, 접을 수 있는 패널에 완벽합니다. 아코디언 동작(하나가 열리면 나머지 닫기)에는 siblings()와 결합하세요. 슬라이드가 가장 흔한 jQuery 애니메이션입니다 — 적절한 ARIA와 짝지으면 부드럽고 접근성 친화적입니다.
// 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()는 지속 시간에 걸쳐 숫자 CSS 프로퍼티를 트위닝합니다. 증분 변화에는 상대 값('+=50')을 쓰세요. 프로퍼티 이름은 반드시 camelCase입니다(margin-left가 아니라 marginLeft). 색은 jQuery Color 플러그인이나 jQuery UI가 필요합니다 — 코어 jQuery는 숫자만 애니메이션합니다. 옵션 형식이 더 많은 제어를 줍니다: queue:false는 순차 대신 병렬 실행입니다. 이징 기본은 'swing'(ease-out)이고, 'linear'는 균등입니다. 여러 프로퍼티를 한 번의 호출로 애니메이션할 수 있습니다.
// 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 없이는 빠른 hover가 애니메이션을 쌓습니다(마우스가 떠난 뒤에도 요소가 계속 애니메이션됩니다) — .animate() 전에 .stop(true)가 이를 막습니다. .finish()는 대기 중인 모든 애니메이션을 즉시 최종 상태로 점프시킵니다. .delay(ms)가 애니메이션 큐에 휴지를 삽입합니다 — 시퀀싱에 유용. 떨림이 쌓이지 않도록 hover 애니메이션에는 항상 .stop()을 짝지으세요.
// .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)순회(Traversing)
위로 이동 (부모)
위로 순회: .parent()(직속 부모), .parents()(문서까지 모든 조상), .parents(selector)가 필터, .closest(selector)는 위로 걸으며 첫 매칭을 반환합니다(자기 자신 포함 — 감싸는 컴포넌트를 찾을 때 가장 흔함). .parentsUntil(selector)는 매칭을 제외한 조상까지 반환합니다. .closest()가 이벤트 위임 패턴의 주력입니다 — 클릭된 요소로부터 감싸는 카드/행/컴포넌트를 찾습니다.
// 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()은 직계 자식만 반환하고(한 수준 아래), .find()는 모든 수준을 내려갑니다. .find()가 가장 흔합니다 — 컨테이너가 주어지면 매칭되는 자손을 찾습니다(예: 폼 안의 모든 폼 필드). 직계 자식만 필요하면 .children()이 더 빠릅니다. .contents()는 텍스트 노드와 주석 노드를 포함합니다(텍스트나 iframe 처리에 유용). 둘 다 선택자로 필터하세요. 전체 문서를 스캔하지 않도록 순회는 .find()로 스코프하세요.
// 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()(모두), .next()/.prev()(바로 옆), .nextAll()/.prevAll()(한 방향 전부), .nextUntil()/.prevUntil()(매칭 전까지). 선택자로 필터하세요. 클래식한 활성 탭 패턴($(this).addClass('active').siblings().removeClass('active'))이 형제들의 상태를 초기화하는 데 siblings를 씁니다. 형제는 같은 부모를 공유합니다 — 중첩이 다르면 형제가 아닙니다.
// 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)은 하나로 줄입니다(음수 n은 끝에서부터). .first()/.last()가 편의 메서드입니다. .slice(start, end)가 범위를 가져옵니다. 복잡한 선택자를 쓰는 대신 순회 후 이들로 선택을 다듬으세요 — 보통 더 명확하고 빠릅니다.
// .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()는 순회 스택을 팝해 이전 집합으로 돌아갑니다 — 순회한 뒤 원본에서 계속 작업하는 읽기 쉬운 체인에 필수입니다. .addBack()(구 .andSelf)이 현재 집합과 이전 집합을 병합해 원본 요소가 이후 연산에 참여합니다. 이들로 강력한 한 줄 체인을 만들 수 있습니다: 자식을 찾고, 수정하고, end()로 부모로 돌아가, 부모를 수정합니다. 순회 구조가 명확하도록 체인을 들여쓰세요.
// .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유틸리티 함수
순회: $.each & $.map
$.each는 배열(인덱스, 값)이나 객체(키, 값)를 순회하는 일반 유틸리티입니다 — 인수 순서가 Array.forEach와 반대입니다. 중단하려면 false를 반환하세요. $.map은 각 항목을 새 배열로 변환합니다(건너뛰려면 null 반환). $.grep은 배열을 필터합니다. 이들은 jQuery의 ES5 이전 순회 유틸리티입니다; 현대 코드는 보통 네이티브 Array 메서드(forEach, map, filter)를 씁니다. $.each를 쓰는 주된 이유는 일반 객체 순회입니다(현대 JS의 Object.entries).
// $.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' 같은 16진수는 아님). 현대 JS에서 Array.isArray와 typeof가 대부분을 커버하지만, $.isPlainObject는 deep-extend 안전에 여전히 편리합니다.
// $.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가 객체를 병합합니다 — 뒤의 프로퍼티가 앞의 것을 이깁니다. 깊은(재귀) 병합에는 첫 인수로 true를, 아니면 얕습니다. 소스를 변형하지 않으려면 항상 첫 인수로 {}를 전달하세요. $.merge는 배열을 연결합니다(첫 번째를 변형). $.inArray는 indexOf입니다(없으면 -1). $.makeArray가 배열류 객체(NodeList, arguments)를 진짜 배열로 바꿉니다 — 현대 코드는 Array.from이나 스프레드 [...nl]를 씁니다.
// $.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 요소 배열을 중복 제거합니다(지금은 거의 불필요). 대부분 현대 네이티브 등가물이 있지만, 여전히 가장 유용한 것은 $.param(AJAX 데이터용)과 $.parseHTML입니다.
// $.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()되면 정리되어 누수를 막습니다.
// 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플러그인 & 확장
플러그인 작성
플러그인은 $.fn(jQuery의 프로토타입)을 확장해 컬렉션에서 호출 가능해집니다. 체이닝을 위해 항상 this를 반환하세요(또는 this의 메서드 결과). 플러그인 안에서 'this'는 jQuery 컬렉션이고, .each() 안에서 'this'는 raw DOM 요소입니다. IIFE로 감싸 jQuery를 통해 $를 안전하게 별칭하세요. $.extend defaults 패턴이 합리적인 기본값과 함께 옵션을 받는 표준 방법입니다. 플러그인은 npm이나 독립 스크립트로 배포하세요.
// 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 ...
})
}메서드가 있는 플러그인
보일러플레이트 플러그인 패턴은 첫 인수로 디스패치되는 methods 객체를 씁니다: 초기화는 $('.c').counter({ start: 5 }), 메서드 호출은 $('.c').counter('increment'). 상태는 $.data에 둡니다. 이 패턴은 슬라이더, 모달, 데이트피커 같은 컴포넌트에서 Vue/React 이전 시대에 인기 있었습니다. 오늘날 상태 있는 UI에는 프레임워크(Vue/React)가 보통 더 나은 선택이지만, 레거시 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(모달). jQuery 뒤에 플러그인 CSS와 JS를 포함하세요. DOM ready에 초기화합니다. 많은 플러그인이 $('#x').plugin('method', args) 같은 메서드 API와 plugin('option', name, val)을 통한 옵션 갱신을 지원합니다.
<!-- 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 -->위젯 팩토리 (jQuery UI)
jQuery UI 위젯 팩토리($.widget)는 상태 있고 상속 친화적인 플러그인을 구조적으로 만드는 방법입니다. _create(생성자), _destroy(정리), _setOption, _on(자동 정리 이벤트 바인딩), _trigger(커스텀 이벤트)를 제공합니다. 옵션은 메서드 API로 노출됩니다: $el.widget('option', name, value). 커스텀 이벤트는 widgetname + eventname으로 발생합니다. jQuery에서 복잡한 상태 UI에는 위젯 팩토리가 가장 견고한 패턴입니다 — 그러나 새 코드는 Vue/React 이전을 고려하세요.
// 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)로 사용자가 내부를 모르고도 깔끔히 해제하게 하기; (5) 옵션을 $.extend로 병합하고 defaults를 노출해 전역 오버라이드 가능하게 하기; (6) destroy에서 정리(이벤트, 데이터, DOM 수정); (7) 충돌을 피하도록 플러그인 이름 네임스페이스화; (8) 유연성을 위해 공개 메서드와 defaults 노출.
// 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속성과 프로퍼티
속성 게터 & 세터
.attr()은 HTML 속성을 읽고 씁니다(마크업 값, 항상 문자열). .prop()는 DOM 프로퍼티를 읽고 씁니다(현재 상태 — 예: 체크박스의 checked 프로퍼티는 사용자 조작 뒤 checked 속성과 다를 수 있음). 불리언 속성(checked, disabled, selected)에는 .prop(), 나머지(href, src, alt, data-*)에는 .attr()을 쓰세요. .data()는 data-*를 읽지만 값을 타입 보존과 함께 내부 캐시에 저장합니다 — DOM 속성 자체를 갱신해야 하면 .attr('data-*')를 쓰세요.
// .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(name)은 data-* 속성을 자동 타입 변환으로 읽습니다(숫자, 불리언, JSON). .data(name, value)로 설정하면 속성이 아닌 내부 캐시에 쓰입니다 — 그래서 .attr('data-name')은 여전히 원본을 반환합니다. 실제 DOM 속성을 갱신하려면(예: CSS 선택자나 서버 측 읽기용) .attr('data-name', value)를 쓰세요. 이 구분이 혼동되면 버그가 납니다. .removeData가 캐시를 지웁니다. 카멜케이스 이름: data-foo-bar는 .data('fooBar')가 됩니다.
<!-- 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()이 폼 값을 균일하게 읽고 씁니다. 라디오는 :checked인 것을 찾아 .val()을 읽으세요. 다중 select에는 .val()이 배열을 반환합니다. .is(':checked')가 깔끔한 불리언 검사입니다. 이 구분이 폼 검증과 직렬화에서 중요합니다.
// 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)클래스 vs 속성
요소 상태를 CSS와 JS에 노출하는 세 가지 방법: 클래스(잘 알려짐, .hasClass), data-* 속성(쿼리 가능, 값 운반), ARIA 속성(스크린 리더 접근 가능). 시각적 상태에는 클래스가 가장 단순합니다. 다중 값 상태(data-state='loading|success|error')에는 data-*가 더 깔끔합니다. 접근성에는 aria-*(aria-pressed, aria-expanded, aria-busy)를 쓰세요 — 시각적 상태와 겹치는 경우가 많아 짝지으세요. 현대 프레임워크가 이를 더 쉽게 하지만, 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()이 폼 값의 만능 게터/세터입니다 — 텍스트 input, textarea, select, 그리고 (라디오/체크박스는) 체크된 것의 값. .serialize()가 URL 인코딩 문자열을 만들고, .serializeArray()가 {name, value} 배열을 줍니다 — .serializeArray().reduce((o, p) => (o[p.name] = p.value, o), {})로 일반 객체로 바꾸세요. 폼 리셋은 raw DOM 요소의 네이티브 .reset() 메서드를 호출하세요(jQuery에는 .reset() 메서드가 없습니다).
// 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()크기와 위치
너비 & 높이 메서드
너비/높이 메서드는 숫자(px)를 반환합니다 — 단위가 붙은 문자열을 반환하는 .css('width')와 다릅니다. .width() = 콘텐츠 박스(CSS width). .innerWidth() = 콘텐츠 + padding. .outerWidth() = 콘텐츠 + padding + border. .outerWidth(true)는 margin 포함. window/document에는 $(window).width()가 뷰포트(보이는 영역)이고, $(document).height()가 전체 페이지 높이입니다(스크롤하면 뷰포트보다 클 수 있음). 세터는 숫자(px)나 문자열('50%', '10em')을 받습니다.
// 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 vs offset
.offset()은 문서 기준입니다(절대 좌표 — 드래그-드롭, 마우스 위치 툴팁에 유용). .position()은 오프셋 부모(position:relative/absolute/fixed를 가진 가장 가까운 조상) 기준입니다 — 컨테이너 안에서 재배치할 때 유용. .offsetParent()가 그 조상을 찾습니다. .scrollTop()/.scrollLeft()가 스크롤 위치를 읽거나 설정합니다 — $(window).scrollTop()이 페이지 스크롤입니다. 오프셋(문서)과 포지션(부모)의 구분이 올바른 위치 계산에 결정적입니다.
// .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으로 디바운스하세요. body 클래스 추가(mobile/desktop)로 CSS가 body.mobile .nav { ... }로 반응하게 합니다. 현대 반응형 코드에는 스타일링은 CSS 미디어 쿼리를, JS에서는 window.matchMedia()를 권합니다 — 더 효율적이고 CSS 브레이크포인트와 정렬됩니다. jQuery의 resize 접근은 레거시 코드에 괜찮지만, CSS + matchMedia가 현대 표준입니다.
// 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를 hidden으로 취급합니다(구버전은 visible로 취급). 뷰포트 감지에는 inViewport 헬퍼가 요소 경계를 스크롤 위치와 비교합니다. 현대 코드는 이 목적으로 IntersectionObserver를 씁니다 — 훨씬 효율적이고(브라우저가 계산, 변경 시에만 콜백) 스크롤 리스너가 필요 없습니다. 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, 타이머 기반 디바운스, 또는 requestAnimationFrame을 쓰세요. 현대적 대안: 스크롤에는 CSS scroll-behavior:smooth, 트리거에는 IntersectionObserver.
// 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)')
})Deferred & Promises
Deferred 만들기
$.Deferred는 jQuery의 프로미스 구현입니다(네이티브 Promise보다 앞섬). 하나를 만든 뒤 .resolve(value)나 .reject(reason)로 settle하세요. .promise()는 읽기 전용 뷰를 반환합니다(소비자가 resolve할 수 없음). 레거시 API는 .then/.catch 대신 .done/.fail/.always를 씁니다. jQuery 3+ Deferred는 thenable이므로 await와 Promise.resolve가 동작합니다. 새 코드에는 네이티브 Promise를 권합니다 — Deferred는 주로 AJAX와 레거시 API에 관련됩니다.
// 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가 모두 resolve되기를 기다린 뒤 각 결과의 배열로 .done을 호출합니다. 하나라도 reject하면 .fail이 즉시 발생합니다. 병렬 비동기 패턴입니다(Promise.all과 유사). 콜백은 입력 deferred마다 배열을 받습니다(AJAX는 각각 [data, status, xhr] 포함). 현대 코드에는 Promise.all + fetch가 더 깔끔하고 resolve된 값을 직접 반환합니다. $.when은 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처럼 새 프로미스를 반환합니다. 비동기 연산을 체이닝하고 값을 변환할 수 있습니다. .then에서 프로미스를 반환하면 이를 기다리고, 값을 반환하면 하류로 전달됩니다. .catch도 3+에서 지원됩니다. jQuery 1.x/2.x의 .then은 비표준 동작이었습니다 — 대신 .pipe를 쓰세요. 가능하면 3+로 업그레이드해 더 깔끔한 비동기 코드를 위해 .then/.catch를 쓰세요.
// 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 newAJAX 프로미스 인터페이스
모든 $.ajax 호출(및 $.get/$.post)은 jqXHR 객체를 반환하며, 이는 프로미스류(.done/.fail/.always 지원)이고 (jQuery 3+에서) thenable입니다(await와 Promise.resolve가 동작). 여러 .done 콜백을 붙일 수 있습니다 — 성공 시 모두 발생합니다. .abort()가 요청을 취소합니다(status 'abort'로 .fail 트리거). 새 코드에는 await $.ajax(...)나 Promise.resolve()로 감싸 네이티브 Promise 체인과 async/await에 깔끔하게 통합하세요.
// $.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)
}
}커스텀 프로미스 파이프라인
어떤 비동기 연산이든 Deferred로 감싸 프로미스를 얻으세요: 만들고, 나중에 resolve/reject하고, .promise()를 반환합니다. jQuery 컬렉션도 .promise()를 노출하며, 요소들의 대기 중인 모든 애니메이션이 완료되면 resolve됩니다 — 애니메이션 배치 뒤 코드를 트리거할 때 유용. 이는 jQuery의 애니메이션 큐를 프로미스 기반 코드와 이어 주어, 애니메이션을 await하거나 AJAX 등 다른 비동기 작업과 깔끔하게 체이닝하게 합니다.
// 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')
})폼
폼 이벤트
submit은 폼 제출 시 발생합니다 — AJAX에는 항상 preventDefault하세요. input은 매 키 입력(텍스트)이나 값 변경 시 발생합니다 — 실시간 검증이나 타이핑하며 검색에 좋습니다. change는 텍스트 input에서는 blur에, 체크박스/라디오/select에서는 즉시 발생합니다. focus/blur는 필드 포커스에서 발생합니다. 동적으로 추가되는 필드에는 폼 위에서 이벤트 위임을 쓰세요. 'change' vs 'input' 구분이 중요합니다: 'input'은 실시간이고, 'change'는 사용자가 편집을 마쳤을 때입니다.
// 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로 일반 객체로 바꾸세요. 둘 다 폼의 현재 상태를 존중합니다(체크박스는 체크됐을 때만 포함; select는 선택된 옵션 사용). 체크박스 값은 value='something'을 설정하지 않으면 기본 'on'입니다. disabled 필드는 제외됩니다. 전체 리로드 없이 AJAX 제출용 폼 데이터를 모으는 표준 방법입니다.
<!-- 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)이 현대 기준선입니다.
// 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())
}
})동적 폼 필드
$()로 요소를 만들어 추가/제거하며 폼 필드를 동적으로 다루세요. 서버가 배열을 받도록 배열식 이름(tags[])을 쓰세요. 이벤트 위임(on('click', '.remove', ...))이 동적으로 추가된 제거 버튼의 클릭을 처리합니다. 재정렬 가능한 필드(위/아래 버튼이나 드래그-드롭)에는 변경마다 이름을 다시 매겨 서버가 깨끗한 시퀀스를 보게 하세요. 이 패턴은 태그 입력, 동적 라인 아이템, 설정 폼에 흔합니다.
// 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하고, 성공/오류를 처리합니다. 이중 제출을 막으려 요청 중 submit 버튼을 비활성화하세요. 다른 코드가 반응하도록 커스텀 이벤트(ajax:success, ajax:error)를 트리거합니다. 성공 시 폼을 리셋합니다. 필드 이름을 오류 메시지에 매핑해 서버 검증 오류를 표시하세요. 이 패턴은 class='ajax'를 더하는 것만으로 어떤 폼도 AJAX 폼으로 만듭니다 — 점진적 향상의 흔한 방법입니다.
// 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')
})
})순회 & 루프
$.each vs .each()
$.each는 배열(인덱스, 값)이나 일반 객체(키, 값)를 순회하는 일반 유틸리티입니다. .each()는 jQuery 컬렉션의 메서드입니다 — 'this'가 raw DOM 요소입니다. 둘 다 중단에는 return false, 계속에는 다른 값을 받습니다. 인수 순서는 (index, value)입니다 — Array.forEach의 (value, index)와 반대. 현대 코드에는 네이티브 forEach/map/for...of가 권장됩니다; jQuery 컬렉션을 다루며 요소가 'this'로 필요할 때 .each()가 여전히 유용합니다.
// $.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 vs .map()
$.map은 배열/객체를 새 배열로 변환합니다(건너뛰려면 null, 펼치려면 배열 반환). 인수 순서는 (value, index)입니다 — $.each와 반대. jQuery 컬렉션의 .map()은 새 jQuery 컬렉션을 반환합니다(일반 배열로는 .get() 호출). .map()에서 null/undefined를 반환하면 그 항목이 제외됩니다. 이들은 네이티브 Array.map보다 앞서지만, 현대 코드는 네이티브 map을 쓰고, jQuery의 .map()은 DOM 컬렉션에서 값 추출에 여전히 편리합니다.
// $.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 루프
큰 컬렉션의 raw 성능에는 $items.eq(i)(jQuery 래퍼) 대신 $items[i](raw DOM 요소)로 클래식 for 루프를 쓰세요 — 반복마다 새 jQuery 객체 생성을 피합니다. .length 프로퍼티가 직접 동작합니다. for...of는 jQuery 컬렉션에서 동작합니다(이터러블). 그러나 성능 문제를 측정하지 않았다면 가독성을 위해 .each()를 권합니다 — 수천 요소 외에는 차이가 거의 느껴지지 않습니다.
// 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(...)가 더 관용적입니다. 부분집합을 모으려면 매칭되는 raw DOM 요소를 배열에 push하고 마지막에 $()로 감싸세요. 값 추출에는 .map().get()이 가장 깔끔한 패턴입니다. 루프에서 jQuery 컬렉션을 만드는 것은 피하세요(각 $() 호출에 오버헤드가 있습니다) — raw 요소를 모아 한 번 감싸세요.
// 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을 만들 때는 문서 프래그먼트에 append하고 한 번에 삽입하세요(항목별 append보다 훨씬 빠릅니다 — append마다 리플로우가 일어남). $(document.createDocumentFragment())가 jQuery 래핑 프래그먼트를 만듭니다. 매우 큰 리스트에는 문자열 연결 + .html()(가장 빠름)이나 템플리팅 라이브러리를 고려하세요. 현대 프레임워크(Vue/React)가 이를 선언적으로 처리하지만, 프래그먼트 패턴은 여전히 유용한 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데이터 저장 & 캐싱
$.data vs .data()
$.data(el, key, val)은 raw DOM 요소의 저수준 함수이고, .data()는 jQuery 컬렉션의 편의 메서드입니다. 둘 다 내부 캐시에(DOM이 아님) 값을 저장하므로 속성 접근보다 빠릅니다. .data()는 data-* 속성도 타입 변환으로 자동 읽습니다(숫자, 불리언, JSON). .data(key, val)로 설정하면 data-* 속성은 갱신되지 않습니다 — 그 용도에는 .attr('data-key', val)을 쓰세요. 지우려면 $.removeData(el, key)나 .removeData(key)를 쓰세요.
// $.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을 오염시키지 않고 각 요소와 연관된 설정, 카운터, flag, 객체를 저장합니다. 인수 없이 .data()를 호출하면 저장된 모든 데이터를 객체로 반환합니다. 객체를 저장하고 변형하면 저장된 참조가 변형됩니다(다시 설정할 필요 없음). 내부 캐시는 요소가 .remove()로 제거되면 자동 정리되어 메모리 누수를 막습니다 — 그러나 raw DOM 메서드(parentNode.removeChild)로 제거하면 정리되지 않습니다.
// 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 객체는 raw DOM 요소와 구분되도록 $ 접두사($boxes, $nav)를 붙입니다. 주의: 캐시된 선택은 DOM이 바뀌면(매칭되는 요소를 추가/제거하면) 낡아집니다. 동적 콘텐츠 삽입 후에는 재조회하세요. 이벤트 핸들러에는 핸들러 밖(같은 스코프)에 캐시해 이벤트마다 재조회를 피하세요.
// 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()은 raw 문자열을 읽습니다. 여러 단어 이름은 HTML에서 kebab-case(data-foo-bar)로, JS에서 camelCase(.data('fooBar'))입니다. JSON 값에는 HTML에서 작은따옴표로 JSON(큰따옴표 사용)을 감싸세요. .attr()로 갱신한 data-*는 DOM에 반영되고, .data()는 캐시에만 씁니다.
<!-- 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('')로 자식을 지우지 마세요 — 데이터/이벤트가 정리되지 않아 메모리 누수가 납니다. 플러그인에는 이벤트를 해제하고 데이터를 제거하는 destroy 메서드를 노출하세요. jQuery의 자동 정리가 raw DOM 제거보다 .remove()를 쓰는 주된 이유입니다.
// .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)커스텀 애니메이션
.animate() 기본
.animate()는 지속 시간에 걸쳐 숫자 CSS 프로퍼티를 트위닝합니다. 증분 변화에는 상대 값('+=50', '-=20')을 쓰세요. 프로퍼티 이름은 반드시 camelCase입니다(margin-left가 아니라 marginLeft). 특수 값 'toggle', 'show', 'hide'는 해당 메서드처럼 동작합니다. 숫자는 픽셀이 기본입니다. 색은 jQuery Color 플러그인이 필요합니다 — 코어 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가 있습니다.
// 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()가 다음 대기 항목으로 전진합니다.
// 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 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 선택자가 애니메이션 중인 요소와 매칭됩니다. 마우스가 빠르게 들어가고 나올 때 쌓임을 막으려 hover 기반 애니메이션에 항상 .stop(true)를 짝지으세요 — 없으면 애니메이션이 큐에 쌓여 마우스가 떠난 뒤에도 오래 재생되어 떨리는 동작이 됩니다.
// .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 */ }이벤트 위임
왜 위임인가?
이벤트 위임은 부모에 하나의 핸들러를 바인딩하며, 자식의 클릭이 버블링되어 이를 트리거합니다. 이점: (1) N개 대신 하나의 핸들러(메모리), (2) 동적으로 추가된 요소에 자동 동작, (3) 더 빠른 셋업(바인딩 1회 vs N회). .on()의 두 번째 인수('li')가 선택자 필터입니다 — 핸들러 안의 'this'는 부모가 아니라 매칭된 자식입니다. 자식들이 동작을 공유하는 모든 목록, 테이블, 컨테이너에 위임을 쓰세요. 유일한 비용은 이벤트당 약간의 오버헤드(선택자 검사)로 무시할 수준입니다.
// 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의 두 위임 핸들러가 현재와 미래의 모든 항목에 대해 삭제 버튼과 항목 토글을 처리합니다. 새 <li> 추가에 재바인딩이 필요 없습니다. 삭제 버튼의 e.stopPropagation()이 li 클릭도 함께 발생하는 것을 막습니다(삭제할 때 .done이 토글되 는 것을 방지). .closest('li')가 클릭된 버튼에서 감싸는 <li>를 찾습니다. 이 패턴이 프레임워크 이전 jQuery SPA의 기초였으며 — 위젯류 UI에 여전히 유용합니다.
<!-- 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>위임 vs 직접 바인딩
직접 바인딩은 핸들러를 매칭된 요소에 붙입니다; 위임 바인딩은 부모에 붙이고 선택자로 필터합니다. 핸들러 안의 핵심 차이: 직접 바인딩에서 e.currentTarget === this === 요소입니다. 위임에서 e.currentTarget은 부모(핸들러가 바인딩된 곳)이고, this는 매칭된 자식(선택자 매칭)이며, e.target은 실제 클릭된 요소입니다(매칭된 자식의 자손일 수 있음). 위임 핸들러에서 부모에 접근하려면 e.delegateTarget을 쓰세요.
// 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)
})위임 핸들러 해제
네임스페이싱(click.task)이 다른 핸들러에 영향 없이 특정 핸들러를 해제하는 가장 깔끔한 방법입니다. .off('click', 'li')는 그 선택자와 매칭되는 위임 핸들러를 제거합니다. .off('click')은 모든 click 핸들러(직접과 위임)를 제거합니다. .off()는 전부 제거합니다 — 신중히 쓰세요. 특정 핸들러를 제거하려면 원래 함수 참조를 전달하세요. 플러그인에는 항상 이벤트를 네임스페이스(click.myplugin)해 사용자가 내부를 모르고도 깔끔히 해제하게 하세요.
// 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에 주의하세요: 조상의 위임 핸들러 발생을 막습니다. 자식이 전파를 멈추면 부모의 위임 핸들러는 절대 실행되지 않습니다. 트레이드오프: 위임은 유연하지만 이벤트당 작은 오버헤드(선택자 매칭)를 더합니다 — 보통 무시 가능하지만 거대한 페이지에서는 중요합니다.
// 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모범 사례
성능 팁
핵심 성능 팁: (1) 선택을 캐시; (2) 쿼리를 .find()로 컨테이너에 스코프; (3) #id 선택자 선호(내부에서 getElementById 사용); (4) * 피하기; (5) 이벤트 위임; (6) 프래그먼트로 DOM 업데이트 배치 — append마다 리플로우가 일어나므로 프래그먼트를 만들어 한 번에 append; (7) 무거운 조작 전에 detach(분리된 요소에 대한 연산은 리플로우를 트리거하지 않음). 1000개 이상 항목의 목록에는 문자열 연결 + .html()이 가장 빠르지만, 프래그먼트가 더 깔끔합니다.
// 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()마다 리플로우가 일어납니다(브라우저가 레이아웃을 재계산). 대량 삽입: (1) HTML 문자열을 만들어 .html()으로 설정(단순 콘텐츠에 가장 빠름); (2) 문서 프래그먼트를 써 한 번에 append(복잡한 요소에 더 깔끔); (3) 컨테이너를 detach하고 수정한 뒤 재부착(수정 중 라이브 DOM의 리플로우를 피함). 1000개 이상 항목에는 항목별 .append()보다 문자열 방식이 훨씬 빠릅니다.
// 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 콜백보다 프로미스 인터페이스(.done/.fail)를 쓰세요. 코드는 IIFE나 ES 모듈로 스코프하세요 — 전역을 오염시키지 마세요. 스크립트가 body 끝에 있으면 $(document).ready를 생략하세요. .animate()보다 CSS 트랜지션/애니메이션을 권합니다(하드웨어 가속, 더 부드러움). 'use strict'를 쓰세요. 새 프로젝트에서는 jQuery보다 프레임워크(Vue/React)가 더 적절한지 평가하세요.
// 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 클래스로 숨기기를 권합니다(스크린 리더가 무시하지 않을 수 있음).
// 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을 꼭 포함해야 한다면 먼저 sanitize하세요(수동 이스케이프나 DOMPurify 같은 라이브러리). 가장 안전한 패턴: $()로 요소를 만들고 동적 콘텐츠에는 .text()를 쓰세요 — $('<li>').text(userInput)가 자동으로 이스케이프합니다. .append('<div>' + data + '</div>') 패턴에는 특히 주의하세요 — data가 사용자 제어라면 XSS 경로입니다.
// 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, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
$('.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흔한 패턴
모달 대화상자
모달 패턴: 오버레이 + 모달을 만들고, body에 append(부모 쌓임 컨텍스트를 피함)하고, 페이드인합니다. 오버레이 클릭(모달 아님)으로 닫습니다 — 감지에는 e.target === this를 쓰세요. Esc 키로 닫습니다. 닫을 때 항상 정리하세요(DOM 제거, 핸들러 해제). 프로덕션에서는 접근성(포커스 트래핑, ARIA, 트리거로 포커스 복귀), 애니메이션, iframe/ajax 모달을 처리하는 라이브러리(Magnific Popup, Bootstrap Modal)를 고려하세요. 위의 패턴은 최소한의 손수 만든 버전입니다.
// 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>')
})탭
클래식 탭 패턴: 탭 링크 클릭이 그 탭을 활성화합니다. 링크의 href(#tab1)가 콘텐츠의 id에 대응합니다. 링크와 콘텐츠 양쪽의 active 클래스가 가시성을 제어합니다(CSS: .tab-content:not(.active) { display: none }). 핸들러는 이벤트 위임을 씁니다(동적으로 추가된 탭 처리). preventDefault가 URL 해시 변경을 막습니다(또는 preventDefault를 생략해 해시 기반 탭 딥링크를 가능하게). 접근성을 위해 role='tab', aria-selected, 키보드 방향키 내비게이션을 추가하세요.
<!-- 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>아코디언
아코디언 패턴: 헤더 클릭이 콘텐츠를 토글합니다. 단일 열림 변형은 하나가 열리면 나머지를 닫습니다(다중 열림에는 .not($h) 블록 제거). 스크린 리더에 상태를 노출하려 aria-expanded를 쓰세요 — CSS가 이를 기반으로 스타일링할 수 있습니다(.acc-header[aria-expanded="true"] { ... }). slideToggle이 콘텐츠를 애니메이션합니다. 헤더에는 <button>을 쓰세요(기본으로 키보드 접근 가능). 항목이 많으면 부모의 이벤트 위임이 각 헤더를 개별 바인딩하는 것을 피합니다.
<!-- 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 flag)를 두세요. 서버가 더 이상 항목이 없다고 하면 스크롤 핸들러를 해제합니다(더 이상 시도하지 않음). 성능을 위해 프래그먼트로 append하세요. 스크롤 핸들러를 스로틀하세요(초당 여러 번 발생) — 디바운스/_.throttle이나(여기처럼) loading flag 검사로 요청 진행 중 스킵하세요. 현대적 대안: 바닥 sentinel 요소의 IntersectionObserver.
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()
}
})실시간 검색 (디바운스)
실시간 검색: 사용자가 타이핑하는 대로 서버에 쿼리하고 결과를 보여줍니다. 디바운스가 필수입니다 — 없으면 매 키 입력마다 요청이 발생합니다(빠른 타이핑 = 수십 개의 요청). 디바운스가 마지막 키 입력 뒤 N ms를 기다렸다 발화합니다. 300ms가 무난한 기본값입니다. 빈 쿼리를 항상 처리하세요(결과 지우기). 프로덕션에서는 응답 순서 꼬임을 피하려 새 요청이 시작될 때 진행 중인 요청을 취소하세요(이전 jqXHR에 .abort()). 현대적 대안: fetch의 AbortController.
// 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)관련 jQuery 스니펫
Copy-paste ready code for common tasks.
Selectors
Select elements by id, class, attribute, and pseudo-filters.
Events & Delegation
Bind handlers with on(), support delegation and namespaced removal.
DOM Manipulation
Get/set text, html, attributes, classes, and insert nodes.
AJAX Requests
Use $.ajax, $.get, $.post, and load with promises.
Effects & Animation
Show, hide, fade, slide, and animate elements.
Traversing the DOM
Navigate relatives and filter the matched set.
Utility Methods
Iterate, merge, and filter with jQuery helpers.
Method Chaining
Chain jQuery methods and use end() to restore context.
Was this helpful?