Snilld

jquery-best-practices

jquery-best-practices

Ensures 100% correct jQuery code following industry best practices, performance optimization, and project-specific patterns. Use when writing or modifying jQuery code in assets/js/.

# jQuery Best Practices

Ensures flawless jQuery code following industry standards, performance optimization, and Creatures & Chronicles project-specific patterns.

## When to Use

- Writing new jQuery code in `assets/js/`
- Modifying existing jQuery event handlers
- Implementing AJAX calls
- DOM manipulation
- Event handling
- Before committing jQuery changes

## Core Principles

1. **Performance First** - Optimize selectors, use event delegation, cache elements
2. **Event Delegation** - Use `$(document).on()` for dynamic content
3. **Use Project Utilities** - Always use `ajaxCall()` from ajax-utils.js
4. **Clean Code** - Follow project patterns, remove event handlers when done
5. **Error Handling** - Always handle AJAX errors with `handleAjaxError()`

## Overview

For detailed patterns and code (event handling, selectors, DOM manipulation, AJAX, project-specific patterns, performance, code organization, common patterns), see **[REFERENCE.md](REFERENCE.md)**.

- **1. Event Handling Patterns** – Delegation, direct binding, removing handlers
- **2. Selector Optimization** – Efficient selectors, caching
- **3. DOM Manipulation** – Batch updates, detach, avoid repeated .find()
- **4. AJAX Patterns** – ajaxCall(), convenience functions, error handling
- **5. Project-Specific Patterns** – Core functions, caching, $.when(), chaining
- **6. Performance Optimization** – Minimize queries, native JS when faster, CSS classes
- **7. Code Organization** – File structure, document ready, JSDoc
- **8. Common Patterns** – Spell/ability handler, character selection, AJAX save, dynamic content

## 9. Validation Checklist

**Before committing, verify:**

✅ **Event Handling:**
- [ ] Using event delegation (`$(document).on()`) for dynamic content
- [ ] Event handlers removed when no longer needed (`.off()`)
- [ ] Selectors are efficient (ID > class > tag)
- [ ] Selectors cached for repeated use

✅ **AJAX:**
- [ ] Using `ajaxCall()` from ajax-utils.js
- [ ] Error handling with `handleAjaxError()`
- [ ] Proper promise handling (`.then()`, `.catch()`)
- [ ] CSRF token included if needed

✅ **DOM Manipulation:**
- [ ] Selectors cached for repeated use
- [ ] DOM updates batched when possible
- [ ] Heavy manipulation uses detach/reattach
- [ ] CSS classes used instead of inline styles when possible

✅ **Performance:**
- [ ] No repeated DOM queries in loops
- [ ] Event delegation attached close to target
- [ ] No jQuery-specific pseudo-selectors (use CSS or .filter())
- [ ] DocumentFragment used for multiple element creation

✅ **Code Quality:**
- [ ] Functions documented with JSDoc
- [ ] `showF()` called at function entry
- [ ] `showD()` used for debug messages
- [ ] Proper error handling

## 10. Common Errors to Avoid

❌ **Direct binding for dynamic content:**
```javascript
// WRONG
$('.spell').click(function() {...});
```

❌ **Not removing event handlers:**
```javascript
// WRONG - Handler never removed
$(document).on('click', '.temporary-element', function() {...});
```

❌ **Repeated DOM queries:**
```javascript
// WRONG
$('#element').addClass('active');
$('#element').find('.child').text('test');
$('#element').removeClass('disabled');
```

❌ **Using raw $.ajax() instead of ajaxCall():**
```javascript
// WRONG
$.ajax({...});
```

❌ **Inefficient selectors:**
```javascript
// WRONG - Slow
$('.spell:even');
$('* .character');
```

❌ **Not handling AJAX errors:**
```javascript
// WRONG
ajaxCall({...}).then(response => {...});
// No .catch() handler
```

❌ **Multiple separate DOM updates:**
```javascript
// WRONG
$('#element').addClass('a');
$('#element').addClass('b');
$('#element').removeClass('c');
```

## 11. Remember

- **Event delegation first** - Always use `$(document).on()` for dynamic content
- **Cache selectors** - Store frequently used selectors in variables
- **Use project utilities** - Always use `ajaxCall()` from ajax-utils.js
- **Remove handlers** - Clean up event handlers when done
- **Batch DOM updates** - Minimize separate DOM operations
- **Handle errors** - Always use `.catch()` with `handleAjaxError()`
- **Document functions** - Use JSDoc for all functions
- **Performance matters** - Optimize selectors, avoid repeated queries

## 12. File Locations Reference

- **AJAX utilities:** `assets/js/include/ajax-utils.js`
- **Core functions:** `assets/js/core.functions.js`
- **Main jQuery files:** `assets/js/`
- **Compiled files:** `assets/js/*-dist.js` (NEVER edit these)

---

**Goal:** Every jQuery implementation must be performant, use event delegation correctly, follow project patterns, and handle errors gracefully.

    Gør brugeroplevelsen bedre.
    Hvilket firma arbejder du for?