Welcome to this comprehensive guide to jQuery! This tutorial is designed to take you from the very basics of jQuery to more advanced topics, providing a solid foundation for using this powerful JavaScript library in your web projects. Each chapter will build upon the last, ensuring a smooth learning curve.
Chapter 1: jQuery Fundamentals
This chapter covers the absolute essentials for getting started with jQuery, from including the library in your project to understanding its core syntax and how to select and interact with elements.
What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
The primary purpose of jQuery is to make it much easier to use JavaScript on your website. It takes many common tasks that require many lines of JavaScript code to accomplish and wraps them into methods that you can call with a single line of code.
Why Use jQuery?
- Simplicity: The syntax is designed to be concise and easy to read, making your code shorter and more organized.
- Cross-Browser Compatibility: jQuery handles many cross-browser inconsistencies, so you can write code that works reliably on browsers like Chrome, Firefox, Safari, and Edge without writing browser-specific workarounds.
- DOM Manipulation: It provides powerful and efficient methods for selecting, traversing, and modifying HTML elements and their attributes.
- Event Handling: jQuery offers a robust event system that simplifies the process of responding to user interactions like clicks, mouse movements, and keyboard input.
- AJAX Support: It has easy-to-use methods for making asynchronous requests to a server, allowing you to update parts of a page without a full page reload.
- Rich Effects and Animations: You can easily create visual effects like hiding, showing, fading, and sliding elements, as well as create custom animations.
- Extensibility: jQuery is highly extensible with thousands of available plugins that add a wide range of functionality.
jQuery Get Started
To start using jQuery, you first need to include the library in your HTML file. You have two main options for this:
Download from jQuery.com: You can download a copy of the jQuery library from the official website, jquery.com, and host it on your own server. You would then link to it in your HTML file:
<script src=”path/to/your/jquery.min.js”></script>
Use a Content Delivery Network (CDN): A CDN is a network of servers that delivers content. Using a CDN can be faster because a user might already have the library cached in their browser from visiting another site. Google, Microsoft, and other companies host jQuery.
<!– Google CDN –>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
It’s best practice to include the jQuery <script> tag just before the closing </body> tag of your HTML document. This allows the HTML content to be parsed and displayed to the user first, which can improve the perceived load time.
The Document Ready Event
A critical concept in jQuery is the “document ready” event. This event fires as soon as the DOM (Document Object Model) is fully loaded and ready to be manipulated. To ensure your jQuery code only runs after the document is ready, you wrap it in a special function:
$(document).ready(function(){
// All your jQuery code goes here...
});
A more common shorthand version is:
$(function(){
// All your jQuery code goes here...
});
jQuery Syntax
The fundamental syntax of jQuery is built around selecting HTML elements and then performing some “action” on them.
The basic syntax is: $(selector).action()
- $: An alias for jQuery. $(selector) is the same as jQuery(selector).
- (selector): The mechanism for “querying” (or finding) HTML elements based on their tag name, ID, class, attributes, and more.
- .action(): A jQuery method that is performed on the selected element(s).
jQuery Selectors
Selectors are used to target HTML elements. jQuery uses CSS-style selectors.
- Element Selector: $(“p”) selects all <p> elements.
- ID Selector: $(“#container”) selects the single element with id=”container”.
- Class Selector: $(“.highlight”) selects all elements with class=”highlight”.
- Attribute Selector: $(“input[type=’text’]”) selects all text input fields.
- Descendant Selector: $(“div p”) selects all <p> elements inside a <div>.
jQuery Events
Events are user actions that jQuery can respond to. You attach an “event handler” function to an element, which runs when the event occurs.
- Common Events: .click(), .mouseenter(), .mouseleave(), .keydown(), .submit(), .change().
Attaching an Event:
$("#myButton").click(function(){
// This code runs when #myButton is clicked.
alert("Button clicked!");
});
- 1
The .on() Method: The modern, recommended way to attach events, as it can handle multiple event types and works on dynamically created elements.
$("#myButton").on("click", function(){
// ...
});
- 2
Chapter 2: jQuery Effects
This chapter explores jQuery’s powerful and easy-to-use methods for creating animations and visual effects to make your websites more dynamic.
jQuery Hide/Show
- hide(): Hides the selected element(s).
- show(): Shows the selected element(s).
- toggle(): Toggles between hiding and showing.
Syntax: $(selector).hide(speed, callback);
- speed (optional): Can be “slow”, “fast”, or milliseconds.
- callback (optional): A function to execute after the effect completes.
jQuery Fade
- fadeIn(): Fades in a hidden element by increasing its opacity.
- fadeOut(): Fades out a visible element.
- fadeToggle(): Toggles between fadeIn() and fadeOut().
- fadeTo(speed, opacity): Fades an element to a specific opacity (0 to 1).
jQuery Slide
- slideDown(): Reveals an element with a sliding-down motion.
- slideUp(): Hides an element with a sliding-up motion.
- slideToggle(): Toggles between slideDown() and slideUp(). This is great for accordions and collapsible panels.
jQuery Animate
The animate() method performs a custom animation of a set of CSS properties. Syntax: $(selector).animate({params}, speed, callback);
- params: An object of CSS properties to animate (e.g., {left: ‘250px’, opacity: 0.5}).
- It can only animate numeric properties (e.g., width, not backgroundColor).
- You can use relative values: width: ‘+=50px’.
jQuery stop()
The stop() method stops an animation before it is finished. This is crucial for preventing animation queues from building up, especially with hover events.
Syntax: $(selector).stop(clearQueue, jumpToEnd);
- stop(true, true) is a common way to clear the queue and complete the current animation instantly.
jQuery Callback Functions
A callback is a function executed after the current effect is finished. This ensures that actions happen sequentially.
Incorrect (without callback):
$("p").hide(1000);
alert("Paragraph hidden."); // Alert appears immediately.
Correct (with callback):
$("p").hide(1000, function(){
alert("Paragraph hidden."); // Alert appears after hiding is complete.
});
jQuery Chaining
Chaining allows you to run multiple commands on the same selection, one after the other, in a single statement. This makes code concise and efficient.
$(“#myElement”).css(“color”, “red”).slideUp(2000).slideDown(2000);
Chapter 3: jQuery HTML/DOM Manipulation
This chapter covers how to get, set, add, and remove HTML content and attributes, giving you full control over the structure and content of your page.
jQuery Get Content and Attributes
- text(): Gets the combined text content of element(s).
- html(): Gets the HTML content (including tags) of the first element.
- val(): Gets the value of form elements.
- attr(‘attributeName’): Gets the value of an attribute.
jQuery Set Content and Attributes
The same methods are used for setting content by passing an argument.
- text(“New text”): Sets the text content.
- html(“<b>New HTML</b>”): Sets the HTML content.
- val(“New value”): Sets the value of a form field.
- attr(‘href’, ‘http://new.com’): Sets an attribute’s value.
jQuery Add Elements
- append(content): Inserts content at the end of the selected element(s).
- prepend(content): Inserts content at the beginning.
- after(content): Inserts content after the element(s).
- before(content): Inserts content before the element(s).
jQuery Remove Elements
- remove(): Removes the selected element(s) entirely (including events).
- empty(): Removes the child elements from the selected element(s), leaving the element itself.
jQuery CSS Classes
Manipulating classes is the preferred way to change an element’s style.
- addClass(‘className’): Adds a class.
- removeClass(‘className’): Removes a class.
- toggleClass(‘className’): Toggles a class on or off.
- hasClass(‘className’): Checks if an element has a class, returns true or false.
jQuery css() Method
Gets or sets CSS properties directly.
- Get: var color = $(“p”).css(“color”);
- Set One: $(“p”).css(“color”, “blue”);
- Set Many: $(“p”).css({“color”: “blue”, “font-size”: “120%”});
jQuery Dimensions
Get and set the width and height of elements.
- width() / height(): The element’s width/height, excluding padding, border, and margin.
- innerWidth() / innerHeight(): Includes padding.
- outerWidth() / outerHeight(): Includes padding and border.
- outerWidth(true) / outerHeight(true): Includes padding, border, and margin.
Chapter 4: jQuery DOM Traversing
Traversing means moving through the DOM tree to find elements based on their relationship to a starting element. This chapter covers how to move up, down, and sideways.
Traversing Ancestors (Up)
- parent(): Gets the direct parent.
- parents(): Gets all ancestors. Can be filtered (e.g., parents(“div”)).
- closest(selector): Gets the first ancestor that matches the selector. Very useful.
Traversing Descendants (Down)
- children(): Gets the direct children of an element.
- find(selector): Gets all descendants that match the selector, no matter how deep they are nested.
Traversing Siblings (Sideways)
- siblings(): Gets all elements at the same level.
- next(): Gets the very next sibling.
- prev(): Gets the very previous sibling.
- nextAll() / prevAll(): Gets all following or preceding siblings.
jQuery Filtering
These methods reduce a set of matched elements.
- first() / last(): Gets the first or last element in the set.
- eq(index): Gets the element at a specific index.
- filter(selector): Reduces the set to only elements matching the selector.
- not(selector): Removes elements matching the selector from the set.
Chapter 5: jQuery AJAX
AJAX (Asynchronous JavaScript and XML) is about loading data from the server and updating parts of a page without a full refresh. jQuery makes AJAX incredibly simple.
jQuery AJAX Intro
AJAX allows you to request text, HTML, XML, or JSON from a remote server using both HTTP GET and HTTP POST requests. jQuery provides several methods for AJAX functionality. The core method is $.ajax(), but there are simpler shorthand methods for common tasks.
The load() Method
The load() method loads data from a server and puts the returned HTML into the selected element.
Syntax: $(selector).load(URL, data, callback);
- URL: The URL you wish to load.
- data (optional): A key/value pair object to send with the request.
- callback (optional): A function to run after the load is complete.
Example:
// Load the content of "content.html" into the #result div.
$("#result").load("content.html", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("Content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
You can also load specific fragments of a file: $(“#result”).load(“content.html #p1”);
jQuery Get/Post Methods
- $.get(URL, callback): Requests data from the server using an HTTP GET request.
- $.post(URL, data, callback): Requests data from the server using an HTTP POST request.
Example with $.get():
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
Example with $.post():
$.post("demo_test_post.asp",{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
Chapter 6: jQuery Miscellaneous
This chapter covers a few useful utilities and concepts that don’t fit into the other categories.
jQuery noConflict()
Other JavaScript libraries (like Prototype, MooTools, or even different versions of jQuery) might also use the $ symbol. To avoid conflicts, you can use the $.noConflict() method. This method releases jQuery’s control of the $ variable, so other scripts can use it.
$.noConflict();
// From now on, you must use the "jQuery" variable name instead of "$"
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery("p").text("jQuery is still working!");
});
});
You can also create your own alias:
var jq = $.noConflict();
jq(function(){
// Use jq here
});
jQuery Filters
Filters are a type of selector that refine a selection, often based on position or state. While we saw some in the Selectors section (like :first), there are many others.
- :first / :last: Selects the first/last element.
- :even / :odd: Selects even/odd indexed elements (0-based).
- :eq(index) / :gt(index) / :lt(index): Selects elements at an index that is equal to, greater than, or less than the specified index.
- :header: Selects all header elements (<h1> through <h6>).
- :animated: Selects all elements that are currently being animated.
- :focus: Selects the element that currently has focus.
- :contains(text): Selects elements containing the specified text.
- :has(selector): Selects elements that contain at least one element matching the selector.
- :empty: Selects elements that have no children (including text nodes).
- :parent: Selects elements that have at least one child node.
- Input Filters: :input, :text, :password, :checkbox, :submit, etc.
Example: $(“tr:odd”).css(“background-color”, “#f2f2f2”); // Stripes a table
Chapter 7: jQuery Examples & Learning Resources
Theory is important, but practice is essential. This section provides ideas for applying your knowledge and outlines a path for continued learning.
jQuery Examples
The best way to learn is by building. Try creating:
- An image gallery with next/previous buttons.
- An interactive FAQ section using slideToggle().
- A to-do list where you can add and remove items using append() and remove().
- A contact form that uses $.post() to submit data without a page refresh and provides feedback to the user.
- A “Scroll to Top” button that appears after scrolling down the page.
jQuery Editor / Playground
Using an online code editor is a great way to experiment without setting up a local environment. Websites like CodePen, JSFiddle, and CodeSandbox allow you to write HTML, CSS, and JavaScript and see the results instantly.
jQuery Quiz & Exercises
Test your knowledge. Create small challenges for yourself or find them online. For example:
- “Select all <li> elements that are children of a <ul> and give them a blue border.”
- “When a button is clicked, fade out all images with the class .old.”
jQuery Syllabus & Study Plan
A structured plan can help you master jQuery:
- Week 1: Focus on Chapters 1 & 2 (Fundamentals & Effects). Re-create every example.
- Week 2: Focus on Chapters 3 & 4 (DOM Manipulation & Traversing). Build a simple to-do list.
- Week 3: Focus on Chapter 5 (AJAX). Build a simple app that loads data from an external file or a public API.
- Week 4: Focus on Chapter 6 (Misc) and practice by building a more complex project combining everything you’ve learned.
jQuery Certificate
While jQuery itself doesn’t offer an official certificate, many online learning platforms (like Coursera, Udemy, freeCodeCamp) offer web development courses that cover jQuery and provide a certificate upon completion. This can be a valuable addition to your resume.
Chapter 8: jQuery References
This section is a quick reference guide to the most common jQuery objects and methods. For a complete list, always refer to the official jQuery API Documentation.
Selectors Reference
- *: All elements.
- #id: Element by ID.
- .class: Elements by class.
- element: Elements by tag name.
- [attribute]: Elements with an attribute.
- :input: All <input>, <textarea>, <select>, and <button> elements.
Events Reference
- click(), dblclick()
- mouseenter(), mouseleave(), hover()
- keydown(), keyup()
- submit(), change(), focus(), blur()
- on(), off()
Effects Reference
- show(), hide(), toggle()
- fadeIn(), fadeOut(), fadeTo(), fadeToggle()
- slideDown(), slideUp(), slideToggle()
- animate(), stop()
HTML/CSS Reference
- html(), text(), val()
- attr(), removeAttr()
- addClass(), removeClass(), toggleClass()
- css()
- width(), height()
Traversing Reference
- parent(), parents()
- children(), find()
- siblings(), next(), prev()
- first(), last(), eq()
AJAX Reference
- load()
- $.ajax()
- $.get()
- $.post()