Getting Started
Setup jQuery
<!-- jQuery via CDN -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Alternatively, download and host locally -->
<script src="js/jquery-3.7.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Alternatively, download and host locally -->
<script src="js/jquery-3.7.1.min.js"></script>
Note: Always include jQuery before your custom scripts. The slim version excludes AJAX and effects modules.
Document Ready
// Shorthand - recommended
$(function() {
// Your code here
});
// Full syntax
$(document).ready(function() {
// Your code here
});
// Alternative syntax
$().ready(function() {
// Your code here
});
$(function() {
// Your code here
});
// Full syntax
$(document).ready(function() {
// Your code here
});
// Alternative syntax
$().ready(function() {
// Your code here
});
Note: Code inside document ready will execute once the DOM is fully loaded.
Selectors
Basic Selectors
// Select by ID
$("#myId")
// Select by class
$(".myClass")
// Select by element
$("div")
$("p")
// Select multiple elements
$("div, p, .myClass")
// Select all elements
$("*")
// Select by attribute
$("[name='email']")
$("[type='text']")
$("#myId")
// Select by class
$(".myClass")
// Select by element
$("div")
$("p")
// Select multiple elements
$("div, p, .myClass")
// Select all elements
$("*")
// Select by attribute
$("[name='email']")
$("[type='text']")
Hierarchy Selectors
// Child selector (direct children)
$("ul > li")
// Descendant selector (any level)
$("div p")
// Next adjacent sibling
$("h2 + p")
// Next siblings
$("h2 ~ p")
// First child
$("li:first-child")
// Last child
$("li:last-child")
// nth child
$("li:nth-child(2)")
$("tr:nth-child(even)")
$("tr:nth-child(odd)")
$("ul > li")
// Descendant selector (any level)
$("div p")
// Next adjacent sibling
$("h2 + p")
// Next siblings
$("h2 ~ p")
// First child
$("li:first-child")
// Last child
$("li:last-child")
// nth child
$("li:nth-child(2)")
$("tr:nth-child(even)")
$("tr:nth-child(odd)")
Filter Selectors
// Visible elements
$("div:visible")
// Hidden elements
$("div:hidden")
// Contains text
$("p:contains('Hello')")
// Empty elements
$("div:empty")
// Elements with at least one child
$("div:parent")
// Has a specific child
$("div:has(p)")
// Form filters
$("input:checked")
$("input:selected")
$("input:disabled")
$("input:enabled")
$("div:visible")
// Hidden elements
$("div:hidden")
// Contains text
$("p:contains('Hello')")
// Empty elements
$("div:empty")
// Elements with at least one child
$("div:parent")
// Has a specific child
$("div:has(p)")
// Form filters
$("input:checked")
$("input:selected")
$("input:disabled")
$("input:enabled")
Form Selectors
// Input selectors
$(":input")
$(":text")
$(":password")
$(":radio")
$(":checkbox")
$(":submit")
$(":reset")
$(":button")
$(":image")
$(":file")
// Form state selectors
$(":focus")
$(":checked")
$(":selected")
$(":disabled")
$(":enabled")
// Custom form selectors
$("input[name='email']")
$("select#country option:selected")
$(":input")
$(":text")
$(":password")
$(":radio")
$(":checkbox")
$(":submit")
$(":reset")
$(":button")
$(":image")
$(":file")
// Form state selectors
$(":focus")
$(":checked")
$(":selected")
$(":disabled")
$(":enabled")
// Custom form selectors
$("input[name='email']")
$("select#country option:selected")
DOM Manipulation
Getting & Setting
// Get text content
var text = $("p").text();
// Set text content
$("p").text("New text");
// Get HTML content
var html = $("div").html();
// Set HTML content
$("div").html("<span>New HTML</span>");
// Get value of form element
var value = $("input").val();
// Set value of form element
$("input").val("New value");
// Get attribute
var src = $("img").attr("src");
// Set attribute
$("img").attr("src", "new-image.jpg");
var text = $("p").text();
// Set text content
$("p").text("New text");
// Get HTML content
var html = $("div").html();
// Set HTML content
$("div").html("<span>New HTML</span>");
// Get value of form element
var value = $("input").val();
// Set value of form element
$("input").val("New value");
// Get attribute
var src = $("img").attr("src");
// Set attribute
$("img").attr("src", "new-image.jpg");
CSS Manipulation
// Get CSS property
var color = $("p").css("color");
// Set single CSS property
$("p").css("color", "red");
// Set multiple CSS properties
$("p").css({
"color": "red",
"font-size": "20px",
"background-color": "#eee"
});
// Add class
$("p").addClass("my-class");
// Remove class
$("p").removeClass("my-class");
// Toggle class
$("p").toggleClass("my-class");
// Check if has class
if ($("p").hasClass("my-class")) {
// Do something
}
var color = $("p").css("color");
// Set single CSS property
$("p").css("color", "red");
// Set multiple CSS properties
$("p").css({
"color": "red",
"font-size": "20px",
"background-color": "#eee"
});
// Add class
$("p").addClass("my-class");
// Remove class
$("p").removeClass("my-class");
// Toggle class
$("p").toggleClass("my-class");
// Check if has class
if ($("p").hasClass("my-class")) {
// Do something
}
DOM Traversal
// Get parent element
$("span").parent();
// Get all ancestors
$("span").parents();
$("span").parents("div"); // Filtered
// Get closest ancestor
$("span").closest("div");
// Get children
$("div").children();
$("div").children("p"); // Filtered
// Find descendants
$("div").find("span");
// Get siblings
$("div").siblings();
$("div").siblings("p"); // Filtered
// Get next sibling
$("div").next();
// Get previous sibling
$("div").prev();
// Get all following siblings
$("div").nextAll();
// Get all preceding siblings
$("div").prevAll();
$("span").parent();
// Get all ancestors
$("span").parents();
$("span").parents("div"); // Filtered
// Get closest ancestor
$("span").closest("div");
// Get children
$("div").children();
$("div").children("p"); // Filtered
// Find descendants
$("div").find("span");
// Get siblings
$("div").siblings();
$("div").siblings("p"); // Filtered
// Get next sibling
$("div").next();
// Get previous sibling
$("div").prev();
// Get all following siblings
$("div").nextAll();
// Get all preceding siblings
$("div").prevAll();
DOM Modification
// Append content
$("div").append("<p>New paragraph</p>");
// Prepend content
$("div").prepend("<p>New paragraph</p>");
// Insert after
$("div").after("<p>New paragraph</p>");
// Insert before
$("div").before("<p>New paragraph</p>");
// Wrap element
$("p").wrap("<div></div>");
// Remove element
$("p").remove();
// Remove element but keep data and events
$("p").detach();
// Empty element (remove all children)
$("div").empty();
// Replace element
$("p").replaceWith("<div>New content</div>");
// Clone element
$("div").clone().appendTo("body");
$("div").append("<p>New paragraph</p>");
// Prepend content
$("div").prepend("<p>New paragraph</p>");
// Insert after
$("div").after("<p>New paragraph</p>");
// Insert before
$("div").before("<p>New paragraph</p>");
// Wrap element
$("p").wrap("<div></div>");
// Remove element
$("p").remove();
// Remove element but keep data and events
$("p").detach();
// Empty element (remove all children)
$("div").empty();
// Replace element
$("p").replaceWith("<div>New content</div>");
// Clone element
$("div").clone().appendTo("body");
Events
Event Handling
// Click event
$("button").click(function() {
// Handle click
});
// Using on() method (recommended)
$("button").on("click", function() {
// Handle click
});
// Multiple events
$("input").on("click keypress", function() {
// Handle multiple events
});
// Event object
$("button").on("click", function(event) {
event.preventDefault();
console.log(event.type); // "click"
console.log(event.target); // The element that was clicked
});
// Remove event handler
$("button").off("click");
// One-time event
$("button").one("click", function() {
// Runs only once
});
$("button").click(function() {
// Handle click
});
// Using on() method (recommended)
$("button").on("click", function() {
// Handle click
});
// Multiple events
$("input").on("click keypress", function() {
// Handle multiple events
});
// Event object
$("button").on("click", function(event) {
event.preventDefault();
console.log(event.type); // "click"
console.log(event.target); // The element that was clicked
});
// Remove event handler
$("button").off("click");
// One-time event
$("button").one("click", function() {
// Runs only once
});
Common Events
// Mouse events
$("div").click(function() {});
$("div").dblclick(function() {});
$("div").hover(function() {});
$("div").mousedown(function() {});
$("div").mouseup(function() {});
$("div").mousemove(function() {});
$("div").mouseenter(function() {});
$("div").mouseleave(function() {});
// Keyboard events
$("input").keydown(function() {});
$("input").keyup(function() {});
$("input").keypress(function() {});
// Form events
$("input").focus(function() {});
$("input").blur(function() {});
$("input").change(function() {});
$("form").submit(function() {});
$("input").select(function() {});
// Document/window events
$(window).resize(function() {});
$(window).scroll(function() {});
$(window).load(function() {});
$(document).ready(function() {});
$("div").click(function() {});
$("div").dblclick(function() {});
$("div").hover(function() {});
$("div").mousedown(function() {});
$("div").mouseup(function() {});
$("div").mousemove(function() {});
$("div").mouseenter(function() {});
$("div").mouseleave(function() {});
// Keyboard events
$("input").keydown(function() {});
$("input").keyup(function() {});
$("input").keypress(function() {});
// Form events
$("input").focus(function() {});
$("input").blur(function() {});
$("input").change(function() {});
$("form").submit(function() {});
$("input").select(function() {});
// Document/window events
$(window).resize(function() {});
$(window).scroll(function() {});
$(window).load(function() {});
$(document).ready(function() {});
Event Delegation
// Basic event delegation
$("#parent").on("click", "button", function() {
// Handle click on button inside #parent
});
// For dynamically added elements
$("table").on("click", "tr", function() {
// Works even for rows added after this code runs
});
// Multiple event handlers with delegation
$("#container").on({
click: function() {
// Handle click
},
mouseenter: function() {
// Handle mouseenter
},
mouseleave: function() {
// Handle mouseleave
}
}, ".dynamic-element");
// Namespaced events
$("button").on("click.myNamespace", function() {});
$("button").off("click.myNamespace"); // Remove only these events
$("#parent").on("click", "button", function() {
// Handle click on button inside #parent
});
// For dynamically added elements
$("table").on("click", "tr", function() {
// Works even for rows added after this code runs
});
// Multiple event handlers with delegation
$("#container").on({
click: function() {
// Handle click
},
mouseenter: function() {
// Handle mouseenter
},
mouseleave: function() {
// Handle mouseleave
}
}, ".dynamic-element");
// Namespaced events
$("button").on("click.myNamespace", function() {});
$("button").off("click.myNamespace"); // Remove only these events
Custom Events
// Triggering events
$("button").click(); // Trigger click event
$("form").submit(); // Trigger submit event
// Using trigger() method
$("button").trigger("click");
// Trigger with custom data
$("button").trigger("click", ["param1", "param2"]);
// Custom events
$("div").on("myCustomEvent", function(event, param1, param2) {
console.log(param1 + " " + param2);
});
$("div").trigger("myCustomEvent", ["Hello", "World"]);
// Event namespaces
$("div").on("click.myPlugin", function() {});
$("div").on("keypress.myPlugin", function() {});
// Remove all events in namespace
$("div").off(".myPlugin");
$("button").click(); // Trigger click event
$("form").submit(); // Trigger submit event
// Using trigger() method
$("button").trigger("click");
// Trigger with custom data
$("button").trigger("click", ["param1", "param2"]);
// Custom events
$("div").on("myCustomEvent", function(event, param1, param2) {
console.log(param1 + " " + param2);
});
$("div").trigger("myCustomEvent", ["Hello", "World"]);
// Event namespaces
$("div").on("click.myPlugin", function() {});
$("div").on("keypress.myPlugin", function() {});
// Remove all events in namespace
$("div").off(".myPlugin");
Effects & Animations
Basic Effects
// Show and hide
$("div").show();
$("div").hide();
$("div").toggle();
// With duration
$("div").show(1000); // 1000ms = 1s
$("div").hide("slow"); // "slow" = 600ms
$("div").toggle("fast"); // "fast" = 200ms
// With callback
$("div").show(1000, function() {
// Animation complete
});
// Fade effects
$("div").fadeIn(1000);
$("div").fadeOut("slow");
$("div").fadeToggle("fast");
$("div").fadeTo(1000, 0.5); // Fade to specific opacity
// Slide effects
$("div").slideDown(1000);
$("div").slideUp("slow");
$("div").slideToggle("fast");
$("div").show();
$("div").hide();
$("div").toggle();
// With duration
$("div").show(1000); // 1000ms = 1s
$("div").hide("slow"); // "slow" = 600ms
$("div").toggle("fast"); // "fast" = 200ms
// With callback
$("div").show(1000, function() {
// Animation complete
});
// Fade effects
$("div").fadeIn(1000);
$("div").fadeOut("slow");
$("div").fadeToggle("fast");
$("div").fadeTo(1000, 0.5); // Fade to specific opacity
// Slide effects
$("div").slideDown(1000);
$("div").slideUp("slow");
$("div").slideToggle("fast");
Custom Animations
// Basic animate
$("div").animate({
left: "250px",
opacity: "0.5",
height: "+=150px"
}, 1000);
// With easing
$("div").animate({
left: "250px"
}, 1000, "linear");
// With callback
$("div").animate({
left: "250px"
}, {
duration: 1000,
complete: function() {
// Animation complete
}
});
// Multiple animations in queue
$("div").animate({left: "250px"}, 1000)
.animate({top: "250px"}, 1000)
.animate({left: "0"}, 1000)
.animate({top: "0"}, 1000);
// Stop animations
$("div").stop(); // Stop current animation
$("div").stop(true); // Stop all queued animations
$("div").stop(true, true); // Stop and complete current animation
// Delay between animations
$("div").hide(1000).delay(2000).show(1000);
$("div").animate({
left: "250px",
opacity: "0.5",
height: "+=150px"
}, 1000);
// With easing
$("div").animate({
left: "250px"
}, 1000, "linear");
// With callback
$("div").animate({
left: "250px"
}, {
duration: 1000,
complete: function() {
// Animation complete
}
});
// Multiple animations in queue
$("div").animate({left: "250px"}, 1000)
.animate({top: "250px"}, 1000)
.animate({left: "0"}, 1000)
.animate({top: "0"}, 1000);
// Stop animations
$("div").stop(); // Stop current animation
$("div").stop(true); // Stop all queued animations
$("div").stop(true, true); // Stop and complete current animation
// Delay between animations
$("div").hide(1000).delay(2000).show(1000);
AJAX
AJAX Methods
// $.ajax() - low level interface
$.ajax({
url: "test.html",
method: "GET",
data: {name: "John", location: "Boston"},
success: function(result) {
console.log(result);
},
error: function(xhr, status, error) {
console.error(error);
}
});
// $.get() - shorthand for GET requests
$.get("test.html", function(data) {
console.log(data);
});
// $.get() with data
$.get("test.php", {name: "John", time: "2pm"}, function(data) {
console.log(data);
});
// $.post() - shorthand for POST requests
$.post("test.php", {name: "John", time: "2pm"}, function(data) {
console.log(data);
});
// $.getJSON() - get JSON data
$.getJSON("test.json", function(data) {
console.log(data);
});
$.ajax({
url: "test.html",
method: "GET",
data: {name: "John", location: "Boston"},
success: function(result) {
console.log(result);
},
error: function(xhr, status, error) {
console.error(error);
}
});
// $.get() - shorthand for GET requests
$.get("test.html", function(data) {
console.log(data);
});
// $.get() with data
$.get("test.php", {name: "John", time: "2pm"}, function(data) {
console.log(data);
});
// $.post() - shorthand for POST requests
$.post("test.php", {name: "John", time: "2pm"}, function(data) {
console.log(data);
});
// $.getJSON() - get JSON data
$.getJSON("test.json", function(data) {
console.log(data);
});
AJAX Advanced
// Using promises with AJAX
$.get("test.html")
.done(function(data) {
console.log("Success: " + data);
})
.fail(function(xhr, status, error) {
console.error("Error: " + error);
})
.always(function() {
console.log("Request completed");
});
// Loading HTML into an element
$("#result").load("test.html");
// Loading part of HTML
$("#result").load("test.html #container");
// AJAX events
$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});
// AJAX with FormData
var formData = new FormData(document.getElementById("myForm"));
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false
});
$.get("test.html")
.done(function(data) {
console.log("Success: " + data);
})
.fail(function(xhr, status, error) {
console.error("Error: " + error);
})
.always(function() {
console.log("Request completed");
});
// Loading HTML into an element
$("#result").load("test.html");
// Loading part of HTML
$("#result").load("test.html #container");
// AJAX events
$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});
// AJAX with FormData
var formData = new FormData(document.getElementById("myForm"));
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false
});
Utilities
Utility Methods
// $.each() - iterate over arrays and objects
$.each(["a", "b", "c"], function(index, value) {
console.log(index + ": " + value);
});
$.each({name: "John", age: 30}, function(key, value) {
console.log(key + ": " + value);
});
// $.extend() - merge objects
var object = $.extend({}, object1, object2);
// $.trim() - remove whitespace
var str = $.trim(" hello world "); // "hello world"
// $.inArray() - find value in array
var arr = ["a", "b", "c"];
var index = $.inArray("b", arr); // 1
// $.isArray() - check if array
$.isArray([1, 2, 3]); // true
// $.isFunction() - check if function
$.isFunction(function() {}); // true
// $.isNumeric() - check if numeric
$.isNumeric("123"); // true
$.isNumeric("abc"); // false
// $.type() - get type of object
$.type("hello"); // "string"
$.type(true); // "boolean"
$.type([1, 2, 3]); // "array"
$.each(["a", "b", "c"], function(index, value) {
console.log(index + ": " + value);
});
$.each({name: "John", age: 30}, function(key, value) {
console.log(key + ": " + value);
});
// $.extend() - merge objects
var object = $.extend({}, object1, object2);
// $.trim() - remove whitespace
var str = $.trim(" hello world "); // "hello world"
// $.inArray() - find value in array
var arr = ["a", "b", "c"];
var index = $.inArray("b", arr); // 1
// $.isArray() - check if array
$.isArray([1, 2, 3]); // true
// $.isFunction() - check if function
$.isFunction(function() {}); // true
// $.isNumeric() - check if numeric
$.isNumeric("123"); // true
$.isNumeric("abc"); // false
// $.type() - get type of object
$.type("hello"); // "string"
$.type(true); // "boolean"
$.type([1, 2, 3]); // "array"
Data Methods
// Store data on element
$("div").data("key", "value");
// Get data from element
var value = $("div").data("key");
// Store multiple values
$("div").data({
key1: "value1",
key2: "value2"
});
// Remove data
$("div").removeData("key");
// Check if element has data
var hasData = $("div").hasData();
// $.data() - low level interface
$.data(document.getElementById("myDiv"), "key", "value");
// $.hasData() - check if element has data
$.hasData(document.getElementById("myDiv"));
// $.removeData() - remove data from element
$.removeData(document.getElementById("myDiv"), "key");
$("div").data("key", "value");
// Get data from element
var value = $("div").data("key");
// Store multiple values
$("div").data({
key1: "value1",
key2: "value2"
});
// Remove data
$("div").removeData("key");
// Check if element has data
var hasData = $("div").hasData();
// $.data() - low level interface
$.data(document.getElementById("myDiv"), "key", "value");
// $.hasData() - check if element has data
$.hasData(document.getElementById("myDiv"));
// $.removeData() - remove data from element
$.removeData(document.getElementById("myDiv"), "key");
Best Practices
Performance
// Cache jQuery objects
var $div = $("div");
$div.addClass("active");
// Use ID selectors when possible
$("#myId") // Fast
$(".myClass") // Slower
// Be specific with selectors
$("div.myClass") // Better than just .myClass
// Avoid excessive specificity
$("#container div.myClass") // Good
$("body #container div.myClass ul li a") // Too specific
// Use find() for context
$("#container").find(".myClass"); // Faster
$("#container .myClass"); // Slower
// Chain methods when possible
$("div").addClass("active").show().html("Hello");
// Use event delegation
$("#container").on("click", ".item", function() {});
// Detach elements before manipulation
var $div = $("#myDiv").detach();
// Manipulate $div
$div.appendTo("body");
var $div = $("div");
$div.addClass("active");
// Use ID selectors when possible
$("#myId") // Fast
$(".myClass") // Slower
// Be specific with selectors
$("div.myClass") // Better than just .myClass
// Avoid excessive specificity
$("#container div.myClass") // Good
$("body #container div.myClass ul li a") // Too specific
// Use find() for context
$("#container").find(".myClass"); // Faster
$("#container .myClass"); // Slower
// Chain methods when possible
$("div").addClass("active").show().html("Hello");
// Use event delegation
$("#container").on("click", ".item", function() {});
// Detach elements before manipulation
var $div = $("#myDiv").detach();
// Manipulate $div
$div.appendTo("body");
Code Organization
// Use document ready
$(function() {
// Your code here
});
// Namespace your code
var MyApp = {};
MyApp.utils = {
init: function() {
// Initialize
},
method: function() {
// Do something
}
};
// Use IIFE to avoid global pollution
(function($) {
// Your code here
// $ is guaranteed to be jQuery
})(jQuery);
// Use strict mode
(function($) {
"use strict";
// Your code here
})(jQuery);
// Use event namespaces
$("button").on("click.myApp", function() {});
// Use data attributes instead of classes for JS hooks
<div data-js="toggle-item"></div>
$("[data-js='toggle-item']").on("click", function() {});
$(function() {
// Your code here
});
// Namespace your code
var MyApp = {};
MyApp.utils = {
init: function() {
// Initialize
},
method: function() {
// Do something
}
};
// Use IIFE to avoid global pollution
(function($) {
// Your code here
// $ is guaranteed to be jQuery
})(jQuery);
// Use strict mode
(function($) {
"use strict";
// Your code here
})(jQuery);
// Use event namespaces
$("button").on("click.myApp", function() {});
// Use data attributes instead of classes for JS hooks
<div data-js="toggle-item"></div>
$("[data-js='toggle-item']").on("click", function() {});