Web Development - jQuery Documentation
The Write less and Do more for Javascript library
Quick Navigation
Core Concepts
DOM Manipulation
Advanced Topics
Why jQuery?
jQuery simplifies HTML document traversing, event handling, and Ajax interactions.
$(document).ready(function() {
$("button").click(function() {
$("p").slideToggle();
});
});
Powerful Selectors
jQuery selectors allow you to select and manipulate HTML elements
Basic Selectors
Selects all <p> elements
Selects element with id='demo'
Selects elements with class='test'
Attribute Selectors
Selects elements with href attribute
Selects elements with exact href value
Selects elements with href containing 'fueint'
Hierarchy Selectors
Selects all <p> inside <div>
Selects <p> directly inside <div>
Selects <p> immediately after <div>
Interactive Events
jQuery provides elegant methods for handling user interactions with clean, intuitive syntax
1Mouse Events
2Keyboard Events
3Form Events
4Document Events
Pro Tip: Event Delegation
For dynamic elements, use $(document).on('click', '.selector', function)
instead of direct binding. This ensures events work for elements added after page load.
jQuery Effects
Create smooth animations and transitions with jQuery effect methods
Display Effects
.hide()
.show()
.toggle()
Slide Effects
.slideDown()
.slideUp()
.slideToggle()
Fade Effects
.fadeIn()
.fadeOut()
.fadeTo()
.fadeToggle()
Other Effects
.animate()
.delay()
Effect Syntax
$(selector).show([speed, callback]);
Speed Parameters
- Words:
slow
,"normal"
,"fast"
- Milliseconds:
1000
(1 second)
Callback Function
Executes after animation completes. Called once per animated element.
Example Usage
// Fade out with callback $("#box").fadeOut("slow", function() { console.log("Animation complete"); }); // Slide toggle with speed $(".panel").slideToggle(500); // Custom animate $(".item").animate({ left: "250px", opacity: "0.5" }, 1000);
Try these effects:
- •
fadeOut()
- Gradually hides elements - •
slideToggle()
- Toggles slide up/down - •
animate()
- Create custom animations
jQuery HTML Methods
Manipulate HTML content and attributes with jQuery powerful methods
Syntax
Return content:
$(selector).html()
Set content:
$(selector).html(content)
Set with function:
$(selector).html(function(index, currentContent))
Parameters
content
- What it is: The new content to set
- What it can be: Text or HTML (can include tags)
function(index, currentContent)
- index: Position of element (0, 1, 2...)
- currentContent: The elements current HTML
Example
<!DOCTYPE html> <html> <head> <title>jQuery html() Method</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body style={{ textAlign: "center" }}> <h1 style={{ color: "green" }}>Hello World</h1> <h2>Hello Teens</h2> <button>Click</button> <script> $(document).ready(function() { $("button").click(function() { alert($("h2").html()); }); }); </script> </body> </html>
Code Explanation:
- When button is clicked, shows alert with HTML content of <h2>
- Demonstrates reading content with .html()
- Document ready ensures DOM is loaded first
Practical Usage
Setting HTML Content
// Set simple text $("#title").html("New Heading"); // Set HTML content $("#container").html("<div class='alert'>Success!</div>"); // Using function $("li").html(function(index) { return "Item " + (index + 1); });
Getting HTML Content
// Get content var content = $("#article").html(); // Use in condition if ($("#warning").html() === "") { $("#warning").html("<strong>Alert!</strong>"); } // Log all paragraph content $("p").each(function() { console.log($(this).html()); });
jQuery DOM Traversing
Navigate and manipulate elements based on their relationships in the DOM tree
DOM Tree Structure
Relationship Types
Parent
Direct container element
Child
Direct contained element
Sibling
Elements at same level
Ancestor
Any element above in hierarchy
Descendant
Any element below in hierarchy
Practical Examples
Navigation Menu
// Highlight parent menu item $(".menu-item.active").parent() .addClass("bg-[#B45309] text-white"); // Find all child links $(".nav-bar").find("a") .addClass("hover:text-[#B45309]");
Form Validation
// Find closest form $(".error-message").closest("form") .addClass("error-state"); // Get sibling inputs $(".invalid").siblings("input") .addClass("border-red-500");
Traversal Methods
Moving Down
.children()
Direct child elements
.find()
All matching descendants
Moving Up
.parent()
Immediate parent element
.parents()
All ancestor elements
.closest()
First matching ancestor
Moving Sideways
.siblings()
All sibling elements
.next()
Immediate next sibling
.prev()
Immediate previous sibling
.filter()
Reduce matched elements
.first()/.last()
First/last element in set
Practical Examples
Navigation Example
// Highlight parent of active link $(".active").parent().addClass("highlight"); // Find all links in navigation $("#nav").find("a").addClass("text-blue-500"); // Get next sibling of current tab $(".tab.active").next().show();
Form Example
// Find closest form ancestor $("input").closest("form").addClass("needs-validation"); // Get all siblings of error message $(".error").siblings().addClass("border-red-500"); // Filter visible inputs $("input").filter(":visible").val("");
jQuery AJAX & Misc Methods
Powerful tools for asynchronous requests and utility functions
AJAX Methods
AJAX Fundamentals
The jQuery ajax()
method lets you send and receive data between a web browser and server asynchronously.
Syntax:
$.ajax({name:value, name:value, ...})
Common Parameters:
JSON Handling
jQuery provides built-in support for handling JSON data in AJAX requests.
// Example: Fetching JSON data $.ajax({ url: 'https://api.example.com/users', method: 'GET', dataType: 'json', success: function(users) { users.forEach(function(user) { console.log(user.name); }); }, error: function(xhr, status, error) { console.error(error); } });
Miscellaneous Methods
.each()
Iterates over jQuery objects/arrays
$("li").each(function(index, element) { console.log("Item " + (index + 1) + ": " + $(element).text()); });
.data()
Stores/retrieves arbitrary data
$("#myDiv").data("userInfo", { name: "Alice", age: 30 }); // Retrieve $("#myDiv").data("userInfo").name;
.noConflict()
Avoids $ variable conflicts
var jQ = jQuery.noConflict(); jQ("p").text("Updated using jQ");
.param()
Creates query strings
var data = { name: "Bob", city: "New York" }; var queryString = jQuery.param(data); // "name=Bob&city=New%20York"
.index()
Finds element position
var listItem = $("#item3"); var index = $("li").index(listItem); // Returns position (0-based)
Quick Reference
Method | Description |
---|---|
.each() | Loop through elements |
.data() | Get/set element data |
.get() | Get DOM elements as array |
.index() | Find element position |
.toArray() | Convert to JavaScript array |
.removeData() | Remove stored data |
Object-Oriented Programming (OOPs)
Organizing code into objects containing data and behavior
Class
Blueprint for creating objects
Object
Instance of a class
Encapsulation
Bundling data & methods
Inheritance
Child class extends parent
Polymorphism
Same method, different behavior
Abstraction
Hiding complex logic
OOPs in Action
// 1. CLASS (Blueprint) class Vehicle { // Private field (Encapsulation) #mileage; constructor(make, model) { this.make = make; this.model = model; this.#mileage = 0; } // Public method (Abstraction) start() { console.log(`${this.make} ${this.model} started`); } // Encapsulation: Controlled access getMileage() { return this.#mileage; } // Polymorphism (default) honk() { console.log("Beep beep!"); } } // 2. INHERITANCE class ElectricCar extends Vehicle { constructor(make, model, battery) { super(make, model); this.battery = battery; } // 3. POLYMORPHISM honk() { console.log("Silent electric beep!"); } charge() { console.log(`${this.make} charging...`); } } // 4. OBJECT (Instance) const tesla = new ElectricCar("Tesla", "Model 3", "100kWh"); // Usage: tesla.start(); // Inherited tesla.honk(); // Polymorphism tesla.charge(); // Child method tesla.getMileage(); // Encapsulated access
Key Concepts Demonstrated:
- Class → Vehicle is the blueprint
- Object → tesla is the concrete instance
- Encapsulation → #mileage is private
- Inheritance → ElectricCar extends Vehicle
- Polymorphism → Different honk() behaviors
- Abstraction → Simple public interfaces
Output When Executed:
Silent electric beep!
Tesla charging...
0