JQUERY RIFERIMENTO RAPIDO
Selettori, DOM, eventi, AJAX, effetti, navigazione
Selettori
Selettori di Base
$("p") // all
elements
$(".btn") // class selector
$("#main") // ID selector
$("ul > li") // direct children
$("input[type='text']") // attribute selector
Selettori Comuni
| $('*') | Tutti gli elementi |
| $('a, span') | Selettori multipli |
| $(':first') | Primo elemento corrispondente |
| $(':last') | Ultimo elemento corrispondente |
| $(':even') / $(':odd') | Elementi con indice pari/dispari |
| $(':visible') / $(':hidden') | Filtri di visibilità |
| $(':contains(text)') | Elementi che contengono testo |
| $(':has(selector)') | Elementi che contengono un corrispondente |
Manipolazione DOM
Contenuto e Struttura
$("#el").html("Bold"); // set inner HTML
$("#el").text("Plain text"); // set text content
$("ul").append("
New"); // add at end
$("ul").prepend("First"); // add at start
Inserimento e Rimozione
$("
Hello
").insertAfter("
#el"); // insert after
$("
Hi
").insertBefore("
#el"); // insert before
$("
#el").remove(); // remove element from DOM
$("
#el").empty(); // remove all children
Metodi
| .html() | Ottieni/imposta HTML interno |
| .text() | Ottieni/imposta contenuto testuale |
| .append() / .prepend() | Aggiungi figlio alla fine/inizio |
| .after() / .before() | Inserisci fratello dopo/prima |
| .wrap() | Avvolgi l'elemento con un nuovo genitore |
| .clone() | Copia profonda dell'elemento |
| .replaceWith() | Sostituisce l'elemento |
Eventi
Associazione di Eventi
$(".btn").on("click", function () {
$(this).toggleClass("active");
});
$(document).on("click", ".dynamic", handler); // delegation
$(".btn").off("click"); // remove handler
Metodi Abbreviati
| .click(fn) | Gestore click |
| .hover(fnIn, fnOut) | Entrata/uscita del mouse |
| .focus() / .blur() | Focus guadagnato/perso |
| .change(fn) | Valore cambiato (input/select) |
| .submit(fn) | Invio del form |
| .keydown() / .keyup() | Eventi tastiera |
Document Ready
$(document).ready(function () { /* DOM loaded */ });
$(function () { /* shorthand */ });
Effetti e Animazioni
Mostra / Nascondi / Alterna
$("#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
Animazione Personalizzata
$("#el").animate({
opacity: 0.5,
left: "+=50px",
height: "toggle"
}, 1000, function () { /* complete */ });
Metodi degli Effetti
| .fadeIn() / .fadeOut() | Anima l'opacità |
| .fadeToggle() | Alterna con dissolvenza |
| .slideDown() / .slideUp() | Anima l'altezza |
| .animate(props, ms) | Animazione CSS personalizzata |
| .stop() | Ferma l'animazione corrente |
| .delay(ms) | Ritarda il prossimo effetto in coda |
AJAX
Metodi Abbreviati
$.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 Completo
$.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)
});
Opzioni AJAX
| url | URL della richiesta |
| method | Metodo HTTP (GET, POST, ...) |
| data | Dati da inviare |
| dataType | Tipo di risposta atteso |
| contentType | Tipo di contenuto della richiesta |
| success / error | Funzioni di callback |
| headers | Header di richiesta personalizzati |
Navigazione
Navigazione nell'Albero
$("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
Metodi di Navigazione
| .parent() / .parents() | Genitore diretto / tutti gli antenati |
| .children() / .find() | Figli diretti / tutti i discendenti |
| .siblings() | Tutti gli elementi fratelli |
| .next() / .prev() | Fratello successivo/precedente |
| .closest(sel) | Antenato più vicino che corrisponde al selettore |
| .first() / .last() | Primo/ultimo nel set corrispondente |
| .eq(index) | Elemento all'indice |
| .filter(sel) | Riduce agli elementi corrispondenti |
Attributi e CSS
Attributi
$("img").attr("src"); // get attribute
$("img").attr("src", "new.jpg"); // set attribute
$("img").removeAttr("title"); // remove attribute
$("input").prop("checked", true); // set property
CSS e Classi
$(".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
Valori e Serializzazione
$("input").val(); // get value
$("input").val("new value"); // set value
$("form").serialize(); // "name=Alice&age=30"
$("form").serializeArray(); // [{name, value}, ...]
Selettori per Form
| $(":input") | Tutti gli elementi del form |
| $(":checked") | Checkbox/radio selezionati |
| $(":selected") | Elementi option selezionati |
| $(":disabled") | Elementi disabilitati |
| $(":text") | Input di testo |
Utilità
Funzioni per Array e Oggetti
$.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)
Metodi Utili
| $.each(arr, fn) | Itera array o oggetto |
| $.extend(target, ...) | Unisce oggetti (shallow) |
| $.inArray(val, arr) | Indice del valore (-1 se mancante) |
| $.isArray(obj) | Verifica se è un array |
| $.trim(str) | Rimuove spazi iniziali/finali |
| $.parseJSON(str) | Analizza una stringa JSON |
| $.map(arr, fn) | Trasforma gli elementi dell'array |
Pattern Comuni
Chaining
$("ul")
.find("li")
.addClass("item")
.first()
.css("font-weight", "bold");
Pattern Plugin
$.fn.highlight = function (color) {
return this.each(function () {
$(this).css("background", color || "yellow");
});
};
$("p").highlight("pink");
Risoluzione Conflitti
// Avoid $ conflicts with other libraries
jQuery.noConflict();
jQuery(document).ready(function ($) {
$(".btn").click(handler); // $ safe inside
});