# Referensi Cepat jQuery

*Selector, DOM, event, AJAX, efek, traversal*

> Source: jQuery Documentation (api.jquery.com) · MIT

## Selector

### Selector Dasar

```
$("p")               // all <p> elements
$(".btn")            // class selector
$("#main")           // ID selector
$("ul > li")         // direct children
$("input[type='text']") // attribute selector
```

### Selector Umum

| Command | Description |
|---------|-------------|
| `$('*')` | Semua elemen |
| `$('a, span')` | Beberapa selector |
| `$(':first')` | Elemen pertama yang cocok |
| `$(':last')` | Elemen terakhir yang cocok |
| `$(':even') / $(':odd')` | Elemen dengan indeks genap/ganjil |
| `$(':visible') / $(':hidden')` | Filter visibilitas |
| `$(':contains(text)')` | Elemen yang mengandung teks |
| `$(':has(selector)')` | Elemen yang mengandung kecocokan selector |

## Manipulasi DOM

### Konten & Struktur

```
$("#el").html("<b>Bold</b>");   // set inner HTML
$("#el").text("Plain text");     // set text content
$("ul").append("<li>New</li>");  // add at end
$("ul").prepend("<li>First</li>"); // add at start
```

### Sisipkan & Hapus

```
$("<p>Hello</p>").insertAfter("#el");  // insert after
$("<p>Hi</p>").insertBefore("#el");     // insert before
$("#el").remove();     // remove element from DOM
$("#el").empty();      // remove all children
```

### Method

| Command | Description |
|---------|-------------|
| `.html()` | Get/set inner HTML |
| `.text()` | Get/set konten teks |
| `.append() / .prepend()` | Tambah anak di akhir/awal |
| `.after() / .before()` | Sisipkan sibling setelah/sebelum |
| `.wrap()` | Bungkus elemen dengan parent baru |
| `.clone()` | Salin elemen secara mendalam |
| `.replaceWith()` | Ganti elemen |

## Event

### Mengikat Event

```
$(".btn").on("click", function () {
  $(this).toggleClass("active");
});
$(document).on("click", ".dynamic", handler); // delegation
$(".btn").off("click"); // remove handler
```

### Method Shorthand

| Command | Description |
|---------|-------------|
| `.click(fn)` | Handler klik |
| `.hover(fnIn, fnOut)` | Mouse masuk/keluar |
| `.focus() / .blur()` | Fokus diperoleh/hilang |
| `.change(fn)` | Nilai berubah (input/select) |
| `.submit(fn)` | Pengiriman form |
| `.keydown() / .keyup()` | Event keyboard |

### Document Ready

```
$(document).ready(function () { /* DOM loaded */ });
$(function () { /* shorthand */ });
```

## Efek & Animasi

### Tampilkan / Sembunyikan / Toggle

```
$("#el").hide(400);          // hide with animation
$("#el").show(400);          // show with animation
$("#el").toggle();           // toggle visibility
$("#el").fadeIn(600);        // fade in
$("#el").slideDown(400);     // slide down
```

### Animasi Custom

```
$("#el").animate({
  opacity: 0.5,
  left: "+=50px",
  height: "toggle"
}, 1000, function () { /* complete */ });
```

### Method Efek

| Command | Description |
|---------|-------------|
| `.fadeIn() / .fadeOut()` | Animasikan opacity |
| `.fadeToggle()` | Toggle dengan fade |
| `.slideDown() / .slideUp()` | Animasikan tinggi |
| `.animate(props, ms)` | Animasi CSS custom |
| `.stop()` | Hentikan animasi saat ini |
| `.delay(ms)` | Tunda efek antrian berikutnya |

## AJAX

### Method Shorthand

```
$.get("/api/data", function (data) { console.log(data); });
$.post("/api/data", { name: "Alice" }, function (res) {});
$.getJSON("/api/items", function (json) {});
$("#el").load("/fragment.html"); // load HTML into element
```

### $.ajax Lengkap

```
$.ajax({
  url: "/api/data",
  method: "POST",
  data: JSON.stringify({ key: "val" }),
  contentType: "application/json",
  success: (res) => console.log(res),
  error: (xhr) => console.error(xhr.status)
});
```

### Opsi AJAX

| Command | Description |
|---------|-------------|
| `url` | URL request |
| `method` | Metode HTTP (GET, POST, ...) |
| `data` | Data yang dikirim |
| `dataType` | Tipe respons yang diharapkan |
| `contentType` | Tipe konten request |
| `success / error` | Fungsi callback |
| `headers` | Header request custom |

## Traversal

### Navigasi Pohon

```
$("li").parent();           // direct parent
$("li").parents("ul");      // all matching ancestors
$("ul").children("li");     // direct children
$("ul").find(".active");    // all matching descendants
$("li").siblings();         // sibling elements
```

### Method Traversal

| Command | Description |
|---------|-------------|
| `.parent() / .parents()` | Parent langsung / semua ancestor |
| `.children() / .find()` | Anak langsung / semua keturunan |
| `.siblings()` | Semua elemen sibling |
| `.next() / .prev()` | Sibling berikutnya/sebelumnya |
| `.closest(sel)` | Ancestor terdekat yang cocok dengan selector |
| `.first() / .last()` | Pertama/terakhir dalam set yang cocok |
| `.eq(index)` | Elemen pada indeks |
| `.filter(sel)` | Kurangi ke elemen yang cocok |

## Atribut & CSS

### Atribut

```
$("img").attr("src");              // get attribute
$("img").attr("src", "new.jpg");   // set attribute
$("img").removeAttr("title");      // remove attribute
$("input").prop("checked", true);  // set property
```

### CSS & Class

```
$(".box").css("color", "red");     // set single style
$(".box").css({ color: "red", fontSize: "14px" }); // multi
$("p").addClass("highlight");
$("p").removeClass("highlight");
$("p").toggleClass("active");
$("p").hasClass("active");         // returns boolean
```

## Form

### Nilai & Serialisasi

```
$("input").val();              // get value
$("input").val("new value");   // set value
$("form").serialize();         // "name=Alice&age=30"
$("form").serializeArray();    // [{name, value}, ...]
```

### Selector Form

| Command | Description |
|---------|-------------|
| `$(":input")` | Semua elemen form |
| `$(":checked")` | Checkbox/radio yang dicentang |
| `$(":selected")` | Elemen option yang dipilih |
| `$(":disabled")` | Elemen yang dinonaktifkan |
| `$(":text")` | Input teks |

## Utilitas

### Helper Array & Objek

```
$.each([1, 2, 3], function (i, val) { /* iterate */ });
$.each(obj, function (key, val) { /* iterate object */ });
$.extend({}, defaults, options); // merge objects
$.inArray("b", ["a", "b", "c"]); // returns 1 (index)
```

### Method Utilitas

| Command | Description |
|---------|-------------|
| `$.each(arr, fn)` | Iterasi array atau objek |
| `$.extend(target, ...)` | Gabungkan objek (shallow) |
| `$.inArray(val, arr)` | Indeks nilai (-1 jika tidak ada) |
| `$.isArray(obj)` | Periksa apakah array |
| `$.trim(str)` | Hapus spasi di awal/akhir |
| `$.parseJSON(str)` | Parse string JSON |
| `$.map(arr, fn)` | Transformasi elemen array |

## Pola Umum

### Chaining

```
$("ul")
  .find("li")
  .addClass("item")
  .first()
  .css("font-weight", "bold");
```

### Pola Plugin

```
$.fn.highlight = function (color) {
  return this.each(function () {
    $(this).css("background", color || "yellow");
  });
};
$("p").highlight("pink");
```

### Resolusi Konflik

```
// Avoid $ conflicts with other libraries
jQuery.noConflict();
jQuery(document).ready(function ($) {
  $(".btn").click(handler); // $ safe inside
});
```
