Session 8: Introduction to jQuery
Learning Objectives
- Understand JavaScript fundamentals
- Add interactivity to web pages
- Manipulate page elements dynamically
- Handle user interactions
Session Overview
Welcome to our session on jQuery! Today, we'll explore jQuery - a powerful JavaScript library that simplifies DOM manipulation and event handling. By the end of this session, you'll understand how jQuery can enhance your WordPress development skills and make your code more efficient.
What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library created by John Resig in 2006. Its motto is "Write less, do more" - which perfectly captures its purpose. jQuery simplifies:
- HTML document traversal and manipulation
- Event handling
- Animation
- AJAX interactions
The Swiss Army Knife Analogy
Think of jQuery as a Swiss Army knife for JavaScript. While you can accomplish everything with vanilla JavaScript (like having individual tools), jQuery packages the most common operations into a compact, efficient library (like having all tools in one pocket-sized device).
Why Use jQuery?
Even in 2025, jQuery remains relevant for several reasons:
- WordPress Core: WordPress itself uses jQuery extensively, making it essential knowledge for WordPress developers
- Cross-browser compatibility: jQuery handles browser differences for you
- Simplified syntax: Accomplish complex tasks with fewer lines of code
- Vast plugin ecosystem: Thousands of ready-to-use components
- Gentle learning curve: Easy to learn, especially if you already know some JavaScript
Real-World Example: WordPress Admin
Next time you're in the WordPress admin panel, open your browser's developer tools and type jQuery in the console. You'll see jQuery is loaded and used extensively throughout the admin interface for things like:
- Collapsible metaboxes
- Media uploader
- AJAX-based saving of options
- Drag-and-drop interfaces
Getting Started with jQuery
Including jQuery in Your Project
Before using jQuery, you need to include it in your HTML document. There are several ways to do this:
Method 1: Download and Include Locally
<!-- In the head section -->
<script src="js/jquery-3.7.1.min.js"></script>
Method 2: Use a CDN (Content Delivery Network)
<!-- Using Google's CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!-- Or using jQuery's CDN -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
Method 3: Using npm (for modern build systems)
// Install jQuery
npm install jquery
// Import in your JavaScript file
import $ from 'jquery';
WordPress-Specific Inclusion
In WordPress, you typically don't manually include jQuery. Instead, you enqueue it using WordPress's built-in functions:
// In your theme's functions.php or plugin file
function enqueue_jquery() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_jquery');
This ensures jQuery is loaded correctly and prevents duplications if other plugins also require jQuery.
Core jQuery Concepts
The $ Symbol
The dollar sign ($) is a shorthand alias for the jQuery object. It's used to access jQuery's functionality:
// These are equivalent:
jQuery(document).ready(function() {
// Code here
});
$(document).ready(function() {
// Code here
});
// Modern shorthand:
$(function() {
// Code here
});
The Megaphone Analogy
Think of the jQuery $ as a special megaphone that lets you communicate with and control HTML elements. When you wrap an element with $(), you're essentially picking up this megaphone to give commands to that specific element or group of elements.
Selectors: Finding Elements
jQuery uses CSS-style selectors to find elements in the DOM. This is one of its most powerful features:
// Select by ID
$("#header") // Finds the element with id="header"
// Select by class
$(".nav-item") // Finds all elements with class="nav-item"
// Select by tag name
$("p") // Finds all paragraph elements
// Combined selectors
$("ul.menu li") // Finds all list items inside ul with class="menu"
// Attribute selectors
$("a[target='_blank']") // Finds links that open in new tabs
// Pseudo selectors
$("tr:odd") // Finds odd-numbered table rows
Vanilla JS vs. jQuery Comparison
| Task | Vanilla JavaScript | jQuery |
|---|---|---|
| Get element by ID | document.getElementById("header") |
$("#header") |
| Get elements by class | document.getElementsByClassName("nav-item") |
$(".nav-item") |
| Query selector | document.querySelector("ul.menu li") |
$("ul.menu li") |
| Query all selectors | document.querySelectorAll("tr:nth-child(odd)") |
$("tr:odd") |
The Document Ready Event
The document ready event ensures your jQuery code runs after the DOM is fully loaded but before all images and other resources are loaded:
// Traditional syntax
$(document).ready(function() {
// Code runs when DOM is ready
});
// Shorthand syntax
$(function() {
// Same as above
});
The Party Analogy
Think of your webpage as a party. The $(document).ready() function is like saying "Start the party once all the guests (DOM elements) have arrived, but don't wait for them to hang up their coats and get settled (images and other resources to load)." If you want to wait until everything is completely ready, you'd use $(window).on('load', function() { ... }), which is like saying "Start the party once everyone is completely settled in."
DOM Manipulation with jQuery
jQuery shines when it comes to manipulating the DOM. Let's explore the most common operations:
Getting and Setting Content
// Get text content
let headerText = $("#header").text();
// Set text content
$("#header").text("New Header Text");
// Get HTML content
let contentHTML = $("#content").html();
// Set HTML content
$("#content").html("<strong>New bold content</strong>");
// Get form values
let username = $("input[name='username']").val();
// Set form values
$("input[name='username']").val("JohnDoe");
Modifying Attributes and Properties
// Get an attribute
let linkURL = $("a.main-link").attr("href");
// Set an attribute
$("a.main-link").attr("href", "https://example.com");
// Set multiple attributes
$("img.profile").attr({
src: "profile.jpg",
alt: "Profile picture",
width: 100
});
// Remove an attribute
$("a.temp-link").removeAttr("href");
Working with CSS Classes
// Add a class
$("nav li").addClass("active");
// Remove a class
$("nav li.old-item").removeClass("old-item");
// Toggle a class (add if not present, remove if present)
$(".accordion-item").toggleClass("expanded");
// Check if an element has a class
if ($("#signup-btn").hasClass("disabled")) {
// Do something
}
Modifying CSS Styles
// Get a CSS property
let bgColor = $("#header").css("background-color");
// Set a CSS property
$("#header").css("background-color", "#f0f0f0");
// Set multiple CSS properties
$(".highlight").css({
backgroundColor: "#ffff00",
fontWeight: "bold",
padding: "5px"
});
Creating and Manipulating Elements
// Create a new element
let newDiv = $("<div>", {
class: "alert",
text: "This is an alert message!"
});
// Append element to the end inside a container
$("#notifications").append(newDiv);
// Prepend element to the beginning inside a container
$("#notifications").prepend(newDiv);
// Insert before an element
newDiv.insertBefore("#main-content");
// Insert after an element
newDiv.insertAfter("#header");
// Remove an element
$(".temp-notice").remove();
// Empty an element (remove all its children)
$("#comments").empty();
// Clone an element
let duplicateElement = $(".template-item").clone();
Real-World Example: Dynamic Content Loading
In WordPress, you might use jQuery to dynamically load content into a page without refreshing. Here's how you might update a product preview panel:
// When a product thumbnail is clicked
$(".product-thumbnail").on("click", function() {
// Get the product ID from a data attribute
let productId = $(this).data("product-id");
// Update the preview panel with new content
$("#product-preview")
.empty() // Clear existing content
.append("<div class='loading'>Loading...</div>");
// In a real application, you'd fetch the product data via AJAX here
// For example purposes, we'll simulate it with setTimeout
setTimeout(function() {
$("#product-preview")
.empty()
.append("<h3>Product " + productId + "</h3>")
.append("<p>This is the product description for product " + productId + "</p>")
.append("<button class='add-to-cart'>Add to Cart</button>");
}, 500);
});
Event Handling with jQuery
jQuery provides a simplified, cross-browser compatible way to handle events:
Basic Event Handling
// Click event
$("#submit-btn").click(function() {
alert("Button clicked!");
});
// More modern approach with on()
$("#submit-btn").on("click", function() {
alert("Button clicked!");
});
// Mouseover event
$(".hover-item").on("mouseover", function() {
$(this).addClass("hovered");
});
// Mouseout event
$(".hover-item").on("mouseout", function() {
$(this).removeClass("hovered");
});
// Form submission
$("#contact-form").on("submit", function(event) {
// Prevent the default form submission
event.preventDefault();
// Validate and process the form
// ...
});
Event Delegation
Event delegation allows you to attach a single event handler to a parent element that will fire for all descendants matching a selector, now or in the future:
// Without event delegation - only works for existing elements
$(".delete-btn").on("click", function() {
$(this).closest("li").remove();
});
// With event delegation - works for dynamically added elements too
$("#task-list").on("click", ".delete-btn", function() {
$(this).closest("li").remove();
});
The Office Manager Analogy
Event delegation is like having an office manager (parent element) who watches the door and directs visitors (events) to the right employee (child element), even if that employee was just hired today. Instead of training every employee to watch for visitors themselves, you have one person responsible for routing them correctly.