Complete Jquery Mastery
From fundamentals to advanced techniques - master Jquery with our comprehensive guide covering all concepts with practical examples and modern techniques.
Complete jQuery Tutorial
Master jQuery - the "write less, do more" JavaScript library
Introduction to 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.
// Hide all paragraphs when button is clicked
$("#hideBtn").click(function() {
$("p").hide();
});
Why Use jQuery?
- Simplifies HTML DOM manipulation
- Handles events easily
- Provides simple AJAX functionality
- Offers cross-browser compatibility
- Includes effects and animations
- Large ecosystem of plugins
- Lightweight (only ~30KB minified)
Including jQuery
<!-- From CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Local file -->
<script src="js/jquery.min.js"></script>
jQuery Syntax
jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).
$(selector).action();
$
- Sign to access jQuery(selector)
- Query/find HTML elements.action()
- Perform action on selected elements
Document Ready
To prevent any jQuery code from running before the document is finished loading:
$(document).ready(function() {
// jQuery methods go here...
});
// Shorthand version
$(function() {
// jQuery methods go here...
});
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more.
Selector | Example | Description |
---|---|---|
Element | $("p") |
Selects all <p> elements |
ID | $("#test") |
Selects element with id="test" |
Class | $(".test") |
Selects all elements with class="test" |
All | $("*") |
Selects all elements |
Multiple | $("p, div, .test") |
Selects all <p>, <div> and class="test" elements |
Attribute | $("[href]") |
Selects all elements with href attribute |
Descendant | $("div p") |
Selects all <p> elements inside <div> elements |
Child | $("div > p") |
Selects all <p> elements that are direct children of <div> |
Try it yourself:
$(".demo-box").css("background-color", "blue");
jQuery Events
jQuery provides simple methods for attaching event handlers to selections. When an event occurs, the provided function is executed.
// Click event
$("p").click(function() {
$(this).hide();
});
// Double click event
$("p").dblclick(function() {
$(this).hide();
});
// Mouse enter
$("#p1").mouseenter(function() {
alert("You entered p1!");
});
// Mouse leave
$("#p1").mouseleave(function() {
alert("Bye! You now leave p1!");
});
// Key press
$("#input1").keypress(function() {
console.log("Key pressed!");
});
// Form submit
$("#form1").submit(function() {
alert("Submitted");
});
on() Method
The on()
method attaches one or more event handlers for the selected elements.
$("p").on("click", function() {
$(this).css("color", "red");
});
Try it yourself:
$("#demoBtn").click(function() {
$(this).text("Clicked!").css("background-color", "green");
});
jQuery Effects
jQuery provides several methods for creating animation effects on elements.
Basic Effects
// Hide and show
$("#hide").click(function() {
$("p").hide();
});
$("#show").click(function() {
$("p").show();
});
// Toggle
$("button").click(function() {
$("p").toggle();
});
// Fade effects
$("#fadeIn").click(function() {
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
$("#fadeOut").click(function() {
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
// Slide effects
$("#slideDown").click(function() {
$("#panel").slideDown();
});
$("#slideUp").click(function() {
$("#panel").slideUp();
});
Custom Animations
$("button").click(function() {
$("div").animate({
left: '250px',
opacity: '0.5',
height: '+=150px',
width: '+=150px'
});
});
Try it yourself:
$(".demo-box").animate({
left: '100px',
width: '200px',
height: '200px'
}, 1000);
DOM Manipulation
jQuery provides powerful methods for DOM manipulation that make it easy to get and set content and attributes.
Get and Set Content
// Get content
$("#btn1").click(function() {
alert("Text: " + $("#test").text());
});
// Set content
$("#btn2").click(function() {
$("#test").text("Hello world!");
});
// Get HTML
$("#btn1").click(function() {
alert("HTML: " + $("#test").html());
});
// Set HTML
$("#btn2").click(function() {
$("#test").html("<b>Hello world!</b>");
});
// Get value
$("#btn1").click(function() {
alert("Value: " + $("#test").val());
});
// Set value
$("#btn2").click(function() {
$("#test").val("John Doe");
});
Manipulating Attributes
// Get attribute
var href = $("a").attr("href");
// Set attribute
$("a").attr("href", "https://www.example.com");
// Set multiple attributes
$("a").attr({
"href": "https://www.example.com",
"title": "Example"
});
Adding and Removing Elements
// Append
$("p").append("Some appended text.");
// Prepend
$("p").prepend("Some prepended text.");
// After
$("img").after("Some text after");
// Before
$("img").before("Some text before");
// Remove
$("#div1").remove();
// Empty
$("#div1").empty();
jQuery AJAX
AJAX allows you to load data from a server without refreshing the page. jQuery provides several methods for AJAX functionality.
AJAX Methods
// Load content from server
$("#div1").load("demo_test.txt");
// GET request
$.get("demo_test.asp", function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
// POST request
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
// AJAX complete method
$.ajax({
url: "demo_test.txt",
success: function(result) {
$("#div1").html(result);
}
});
$("button").click(function() {
$.ajax({
url: "demo_test.txt",
success: function(result) {
$("#div1").html(result);
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
});
});
jQuery Traversing
jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on their relation to other elements.
Traversing Methods
// Parent
$("span").parent();
// Parents
$("span").parents();
// Parents until
$("span").parentsUntil("div");
// Children
$("div").children();
// Find
$("div").find("span");
// Siblings
$("h2").siblings();
// Next
$("h2").next();
// Next all
$("h2").nextAll();
// Next until
$("h2").nextUntil("h6");
// Previous
$("h2").prev();
// Previous all
$("h2").prevAll();
// Previous until
$("h2").prevUntil("h6");
Try it yourself:
- Item 1
- Item 2
- Item 3
- Item 4
$(".highlight").siblings().css("color", "red");
jQuery Forms
jQuery provides several methods to work with forms and form elements.
Form Methods
// Get form values
$("input").val();
// Set form values
$("input").val("John Doe");
// Textarea
$("textarea").val("Hello world");
// Select dropdown
$("select").val("option2");
// Checkbox
$("input:checkbox").prop("checked", true);
// Radio button
$("input:radio").prop("checked", true);
// Form serialize
$("form").serialize(); // Outputs: name=John&email=john@example.com
Form Events
// Focus
$("input").focus(function() {
$(this).css("background-color", "#cccccc");
});
// Blur
$("input").blur(function() {
$(this).css("background-color", "#ffffff");
});
// Change
$("input").change(function() {
alert("The text has been changed");
});
// Submit
$("form").submit(function() {
alert("Submitted");
});
jQuery Utilities
jQuery provides several utility methods that can be used either with jQuery objects or independently.
Common Utility Methods
// $.each() - iterate over arrays and objects
$.each([1, 2, 3], function(index, value) {
console.log(index + ": " + value);
});
// $.extend() - merge objects
var object = $.extend({}, object1, object2);
// $.trim() - remove whitespace
var str = $.trim(" Hello "); // "Hello"
// $.inArray() - search for value in array
var arr = [1, 2, 3];
var index = $.inArray(2, arr); // 1
// $.isArray() - check if object is array
$.isArray([]); // true
// $.isFunction() - check if object is function
$.isFunction(function() {}); // true
// $.now() - current timestamp
$.now(); // 1634567890123
jQuery Plugins
jQuery plugins extend jQuery's prototype object to provide additional methods that can be used with jQuery objects.
Creating a Plugin
(function($) {
$.fn.greenify = function() {
this.css("color", "green");
return this;
};
}(jQuery));
// Usage
$("p").greenify();
Popular jQuery Plugins
- jQuery UI - Interactions, widgets, effects
- Slick - Carousel/slider plugin
- DataTables - Advanced table interactions
- Magnific Popup - Lightbox and dialog script
- Validate - Form validation plugin
- FullCalendar - Full-sized calendar
jQuery Best Practices
- Always use
$(document).ready()
before executing jQuery code - Cache jQuery selectors in variables for reuse
- Use ID selectors whenever possible (fastest)
- Chain jQuery methods when possible
- Use event delegation for dynamic elements
- Minimize DOM manipulation
- Use the latest version of jQuery
- Consider using vanilla JavaScript for simple tasks
- Use CDN-hosted jQuery for better performance
- Always check if elements exist before manipulating them
- Use
noConflict()
if multiple libraries use$