jQuery Master Guide

Complete jQuery Master Guide

Complete jQuery Master Guide

Learn jQuery from basics to advanced concepts with interactive examples and live coding playground.

🚀 Introduction to jQuery

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.

// Basic jQuery Setup $(document).ready(function() { // Your code here console.log("jQuery is ready!"); }); // Shorthand version $(function() { console.log("Document is ready!"); }); // jQuery vs Vanilla JS // Vanilla JavaScript: document.addEventListener('DOMContentLoaded', function() { // Code here }); // jQuery equivalent: $(function() { // Same code, simpler syntax });

Why Use jQuery?

  • Cross-browser compatibility - Works in all browsers
  • Simplified syntax - Write less, do more
  • CSS3 selectors - Powerful element selection
  • AJAX simplified - Easy asynchronous requests
  • Animations & effects - Built-in animation methods
  • Plugin ecosystem - Thousands of plugins available
  • Chaining - Multiple methods in one line

Getting Started

Include jQuery in your project using CDN:

<!-- Using CDN --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <!-- Local file --> <script src="js/jquery.min.js"></script> <!-- Basic HTML structure --> <!DOCTYPE html> <html> <head> <title>jQuery Example</title> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> </head> <body> <div id="content">Hello World</div> <script> $(document).ready(function() { $('#content').text('Hello jQuery!'); }); </script> </body> </html>

🎯 jQuery Selectors

Basic Selectors

jQuery uses CSS-style selectors to find elements in the DOM.

// Basic Selectors $('#id') // Select by ID $('.class') // Select by class $('element') // Select by tag name $('*') // Select all elements // Examples $('#header') // Element with id="header" $('.menu-item') // All elements with class="menu-item" $('p') // All paragraph elements $('div.container') // All divs with class="container" // Multiple Selectors $('h1, h2, h3') // All h1, h2, and h3 elements $('.btn, .button') // Elements with class btn OR button

Hierarchy Selectors

Select elements based on their relationship to other elements.

// Hierarchy Selectors $('parent > child') // Direct children $('ancestor descendant') // All descendants $('prev + next') // Next adjacent sibling $('prev ~ siblings') // All following siblings // Examples $('ul > li') // Direct li children of ul $('div p') // All p elements inside divs $('h1 + p') // First p after h1 $('h2 ~ p') // All p elements after h2 // Finding Elements $('#container').find('.item') // Find .item within #container $('.parent').children('li') // Direct li children $('li.selected').siblings() // All siblings of selected li $('li:first').next() // Next sibling $('li:last').prev() // Previous sibling

Attribute & Filter Selectors

Advanced selectors for more specific element selection.

// Attribute Selectors $('[attribute]') // Has attribute $('[attribute="value"]') // Attribute equals value $('[attribute!="value"]') // Attribute not equal $('[attribute^="value"]') // Attribute starts with $('[attribute$="value"]') // Attribute ends with $('[attribute*="value"]') // Attribute contains $('[attribute~="value"]') // Attribute contains word // Examples $('[data-toggle]') // Has data-toggle attribute $('input[type="text"]') // Text input fields $('a[href^="https"]') // Links starting with https $('img[src$=".jpg"]') // JPG images $('div[class*="col-"]') // Bootstrap column classes // Filter Selectors $(':first') // First element $(':last') // Last element $(':even') // Even elements (0-indexed) $(':odd') // Odd elements (0-indexed) $(':eq(n)') // Element at index n $(':gt(n)') // Elements after index n $(':lt(n)') // Elements before index n $(':not(selector)') // Elements not matching selector $(':has(selector)') // Elements containing selector // Form Selectors $(':input') // All input elements $(':text') // Text inputs $(':password') // Password inputs $(':radio') // Radio buttons $(':checkbox') // Checkboxes $(':selected') // Selected options $(':checked') // Checked inputs

Try jQuery Selectors

Item 1
Item 2
Item 3 (Special)
Item 4
Item 5

🎮 jQuery Events

Event Methods

jQuery provides simple methods for handling events.

// Basic Event Handling $('#button').click(function() { alert('Button clicked!'); }); // Mouse Events $('.element').click(handler); // Click event $('.element').dblclick(handler); // Double click $('.element').hover(handlerIn, handlerOut); // Hover $('.element').mouseenter(handler); // Mouse enters $('.element').mouseleave(handler); // Mouse leaves $('.element').mousemove(handler); // Mouse moves // Keyboard Events $('#input').keydown(handler); // Key pressed down $('#input').keyup(handler); // Key released $('#input').keypress(handler); // Key pressed // Form Events $('#form').submit(handler); // Form submission $('#input').change(handler); // Value changed $('#input').focus(handler); // Element focused $('#input').blur(handler); // Element blurred // Window Events $(window).resize(handler); // Window resized $(window).scroll(handler); // Window scrolled $(window).load(handler); // Page fully loaded

on() and off() Methods

The recommended way to attach event handlers.

// Using on() method $('#element').on('click', function() { console.log('Clicked!'); }); // Multiple events $('#element').on('click mouseenter', function() { console.log('Click or mouseenter'); }); // Event delegation $('#container').on('click', '.item', function() { console.log('Item clicked:', $(this).text()); }); // Passing data to handler $('#button').on('click', {name: 'John'}, function(event) { console.log('Hello', event.data.name); }); // One-time event $('#button').one('click', function() { console.log('This runs only once'); }); // Removing events $('#element').off('click'); // Remove all click handlers $('#element').off('click', handler); // Remove specific handler // Namespaced events $('#element').on('click.myNamespace', handler); $('#element').off('click.myNamespace');

Event Object

jQuery normalizes the event object across browsers.

$('#element').on('click', function(event) { // Event Properties event.preventDefault(); // Prevent default action event.stopPropagation(); // Stop event bubbling // Target element console.log(event.target); // Original DOM element console.log(event.currentTarget); // Current element in bubble // Mouse position console.log(event.pageX, event.pageY); // Relative to document console.log(event.clientX, event.clientY); // Relative to viewport // Keyboard events console.log(event.key); // Key pressed console.log(event.keyCode); // Key code // Event type console.log(event.type); // "click", "keydown", etc. // Timestamp console.log(event.timeStamp); // Time since page load // Which mouse button console.log(event.which); // 1: left, 2: middle, 3: right }); // Triggering events programmatically $('#button').click(); // Trigger click event $('#button').trigger('click'); // Same as above $('#form').trigger('submit'); // Trigger form submission // Custom events $('#element').on('customEvent', function() { console.log('Custom event triggered'); }); $('#element').trigger('customEvent');

Event Handling Demo

Click or Hover Me!

✨ jQuery Effects

Basic Effects

Simple show/hide effects with optional animations.

// Basic Show/Hide $('#element').show(); // Show element $('#element').hide(); // Hide element $('#element').toggle(); // Toggle visibility // With speed parameter $('#element').show('slow'); // Show slowly $('#element').hide('fast'); // Hide quickly $('#element').toggle(1000); // Toggle in 1 second // With callback $('#element').hide('slow', function() { console.log('Element hidden'); }); // Fade Effects $('#element').fadeIn(); // Fade in $('#element').fadeOut(); // Fade out $('#element').fadeToggle(); // Toggle fade $('#element').fadeTo('slow', 0.5); // Fade to opacity 0.5 // Slide Effects $('#element').slideDown(); // Slide down $('#element').slideUp(); // Slide up $('#element').slideToggle(); // Toggle slide // Chaining effects $('#element') .slideDown('slow') .delay(1000) .fadeOut('slow');

Custom Animations

Create custom animations with the animate() method.

// Basic animation $('#element').animate({ left: '250px', opacity: 0.5, height: '150px', width: '150px' }, 1000); // Duration 1 second // Multiple properties $('#element').animate({ marginLeft: '+=50px', fontSize: '+=2px' }, 500); // Relative animations $('#element').animate({ left: '+=100px' // Move 100px right }, 500); // Queue animations $('#element') .animate({left: '100px'}, 500) .animate({top: '100px'}, 500) .animate({left: '0'}, 500) .animate({top: '0'}, 500); // Easing functions $('#element').animate({ left: '200px' }, 1000, 'swing'); // or 'linear' // Step callback $('#element').animate({ width: '200px' }, { duration: 1000, step: function(now, fx) { console.log('Current width:', now); } }); // Complete callback $('#element').animate({ height: '200px' }, { duration: 1000, complete: function() { console.log('Animation complete!'); } }); // Stop animations $('#element').stop(); // Stop current animation $('#element').stop(true); // Stop all queued animations $('#element').stop(true, true); // Stop and jump to end $('#element').finish(); // Finish all animations

Effects Demo

Animate Me!

🌐 DOM Manipulation

Getting and Setting Content

jQuery makes it easy to read and modify element content.

// Getting Content var text = $('#element').text(); // Get text content var html = $('#element').html(); // Get HTML content var value = $('#input').val(); // Get form value var attr = $('#img').attr('src'); // Get attribute // Setting Content $('#element').text('New text'); // Set text content $('#element').html('New HTML'); // Set HTML content $('#input').val('New value'); // Set form value $('#img').attr('src', 'new.jpg'); // Set attribute $('#img').attr({ // Set multiple attributes 'src': 'new.jpg', 'alt': 'New image' }); // Removing Attributes $('#img').removeAttr('src'); // Remove attribute // CSS Classes $('#element').addClass('active'); // Add class $('#element').removeClass('inactive'); // Remove class $('#element').toggleClass('active'); // Toggle class $('#element').hasClass('active'); // Check if has class // CSS Properties $('#element').css('color', 'red'); // Set single property $('#element').css({ // Set multiple properties 'color': 'red', 'background': 'blue', 'font-size': '20px' }); var color = $('#element').css('color'); // Get property value

Adding and Removing Elements

Dynamically add, remove, or replace elements in the DOM.

// Creating Elements var newDiv = $('
New div
'); // Create new element var newPara = $('

', { // Create with properties text: 'New paragraph', class: 'my-class', css: {color: 'red'} }); // Appending Elements $('#container').append(newDiv); // Insert at end $('#container').prepend(newDiv); // Insert at beginning $('#element').after(newDiv); // Insert after $('#element').before(newDiv); // Insert before // Inserting Elements newDiv.appendTo('#container'); // Append to container newDiv.prependTo('#container'); // Prepend to container newDiv.insertAfter('#element'); // Insert after element newDiv.insertBefore('#element'); // Insert before element // Wrapping Elements $('#element').wrap('

'); // Wrap element $('.items').wrapAll('
'); // Wrap all $('#element').wrapInner(''); // Wrap inner content // Removing Elements $('#element').remove(); // Remove element $('#element').empty(); // Remove children only $('#element').detach(); // Remove but keep data // Replacing Elements $('#old').replaceWith(newDiv); // Replace element newDiv.replaceAll('#old'); // Replace all matching // Cloning Elements var clone = $('#element').clone(); // Clone element var cloneWithData = $('#element').clone(true); // Clone with data and events

Traversing the DOM

Navigate through the DOM tree easily.

// Parent Elements $('#child').parent(); // Immediate parent $('#child').parents('div'); // All parent divs $('#child').parentsUntil('#container'); // Parents until container $('#child').closest('div'); // Closest parent div // Child Elements $('#parent').children(); // All children $('#parent').children('.selected'); // Selected children $('#parent').find('.item'); // Find descendants // Sibling Elements $('#element').siblings(); // All siblings $('#element').siblings('.selected'); // Selected siblings $('#element').next(); // Next sibling $('#element').nextAll(); // All next siblings $('#element').nextUntil('.stop'); // Next until selector $('#element').prev(); // Previous sibling $('#element').prevAll(); // All previous siblings $('#element').prevUntil('.stop'); // Previous until selector // Filtering Elements $('div').first(); // First div $('div').last(); // Last div $('div').eq(2); // Div at index 2 $('div').slice(1, 3); // Divs 1 to 3 $('div').filter('.selected'); // Filter by selector $('div').not('.hidden'); // Exclude elements $('div').has('span'); // Divs containing span // Chaining Traversal $('#container') .find('.item') .first() .next() .addClass('active');

⚡ jQuery AJAX

AJAX Methods

Simplified AJAX requests with jQuery.

// $.ajax() - Full control $.ajax({ url: 'api/data', method: 'GET', dataType: 'json', data: { id: 123 }, success: function(data) { console.log('Success:', data); }, error: function(xhr, status, error) { console.error('Error:', error); }, complete: function() { console.log('Request complete'); } }); // Shorthand methods $.get('api/data', {id: 123}, function(data) { console.log('GET success:', data); }, 'json'); $.post('api/save', {name: 'John'}, function(data) { console.log('POST success:', data); }); $.getJSON('api/data.json', function(data) { console.log('JSON data:', data); }); $.getScript('script.js', function() { console.log('Script loaded'); }); // Load HTML content $('#result').load('content.html #section'); // Load specific section // AJAX Events $(document).ajaxStart(function() { $('#loading').show(); }); $(document).ajaxStop(function() { $('#loading').hide(); }); $(document).ajaxError(function(event, xhr, settings, error) { console.error('AJAX error:', error); }); // Setting defaults $.ajaxSetup({ timeout: 5000, headers: { 'X-Requested-With': 'XMLHttpRequest' } });

AJAX with Promises

Modern approach using jQuery Deferred objects.

// Using Deferred/Promise $.ajax('api/data') .done(function(data) { console.log('Success:', data); }) .fail(function(xhr, status, error) { console.error('Error:', error); }) .always(function() { console.log('Always runs'); }); // Multiple AJAX requests $.when( $.ajax('api/users'), $.ajax('api/posts') ).done(function(users, posts) { console.log('Both requests complete'); console.log('Users:', users[0]); console.log('Posts:', posts[0]); }); // Custom Deferred object function asyncTask() { var deferred = $.Deferred(); setTimeout(function() { if (Math.random() > 0.5) { deferred.resolve('Success!'); } else { deferred.reject('Failed!'); } }, 1000); return deferred.promise(); } asyncTask() .done(function(result) { console.log(result); }) .fail(function(error) { console.error(error); });

AJAX Demo

Try making AJAX requests to public APIs:

Response will appear here...

🔧 jQuery Utilities

Utility Methods

Useful helper functions provided by jQuery.

// Type Checking $.isArray([1,2,3]); // true $.isFunction(function() {}); // true $.isNumeric('123'); // true $.type('hello'); // "string" $.isPlainObject({}); // true $.isEmptyObject({}); // true // Array/Object Operations var arr = $.makeArray(arrayLike); // Convert to array var merged = $.extend({}, obj1, obj2); // Merge objects var cloned = $.extend(true, {}, obj); // Deep clone var filtered = $.grep(array, function(item) { return item > 10; }); // Filter array $.each(array, function(index, value) { console.log(index, value); }); // Iterate array/object var mapped = $.map(array, function(item) { return item * 2; }); // Map array // String Operations var trimmed = $.trim(' hello '); // Trim whitespace var paramStr = $.param({id: 1, name: 'John'}); // Object to query string // Browser Detection (Deprecated but useful) $.browser.webkit; // WebKit browser $.browser.msie; // Internet Explorer $.browser.version; // Browser version // Support Detection $.support.ajax; // AJAX support $.support.boxModel; // Box model support // Queue Management $('#element').queue('fx', function(next) { // Animation queue next(); }); $('#element').dequeue('fx'); // Run next in queue $('#element').clearQueue('fx'); // Clear queue

Data Storage

Store arbitrary data associated with DOM elements.

// Store data on elements $('#element').data('key', 'value'); // Store data var value = $('#element').data('key'); // Retrieve data $('#element').data({ // Store multiple name: 'John', age: 30 }); // Check if data exists var hasData = $('#element').hasData('key'); // Remove data $('#element').removeData('key'); // Remove specific $('#element').removeData(); // Remove all // Data vs Attr $('#element').data('custom', 'value'); // Stores in memory $('#element').attr('data-custom', 'value'); // Stores as attribute // Namespaced data $('#element').data('user.name', 'John'); $('#element').data('user.age', 30); // Data with objects var user = {name: 'John', age: 30}; $('#element').data('user', user); user.name = 'Jane'; // Modifies stored data too!

🧩 jQuery Plugins

Using Plugins

Thousands of plugins extend jQuery's functionality.

// Common jQuery Plugins // 1. jQuery UI - Official UI library $('#datepicker').datepicker(); $('#slider').slider(); $('#dialog').dialog(); $('#sortable').sortable(); // 2. jQuery Validation - Form validation $('#form').validate({ rules: { email: { required: true, email: true } } }); // 3. Slick Carousel - Image slider $('.carousel').slick({ dots: true, infinite: true }); // 4. DataTables - Advanced tables $('#table').DataTable(); // 5. Magnific Popup - Lightbox $('.image-link').magnificPopup({ type: 'image' }); // 6. Select2 - Enhanced select boxes $('.select2').select2(); // 7. FullCalendar - Calendar widget $('#calendar').fullCalendar(); // 8. jQuery Mask - Input masking $('#phone').mask('(000) 000-0000'); // Loading a plugin // 1. Include plugin CSS & JS // 2. Initialize on elements // 3. Configure options // Example: Using a simple plugin $.fn.highlight = function(color) { return this.css('background-color', color || 'yellow'); }; $('p').highlight(); // Makes paragraphs yellow $('h1').highlight('#ff0000'); // Makes h1 red

Creating Plugins

Learn to create your own jQuery plugins.

// Basic Plugin Pattern (function($) { $.fn.myPlugin = function(options) { // Default settings var settings = $.extend({ color: 'blue', text: 'Hello Plugin!' }, options); // Plugin logic return this.each(function() { var $this = $(this); // Apply plugin functionality $this.css('color', settings.color); $this.text(settings.text); // Chainable return this; }); }; })(jQuery); // Using the plugin $('#element').myPlugin({ color: 'red', text: 'Custom Text' }); // Advanced Plugin with Methods (function($) { var methods = { init: function(options) { return this.each(function() { var $this = $(this); var data = $this.data('myPlugin'); if (!data) { data = $.extend({}, $.fn.myPlugin.defaults, options); $this.data('myPlugin', data); } // Initialization code }); }, show: function() { return this.each(function() { $(this).show(); }); }, hide: function() { return this.each(function() { $(this).hide(); }); } }; $.fn.myPlugin = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist'); } }; // Default settings $.fn.myPlugin.defaults = { color: '#000', speed: 400 }; })(jQuery); // Using advanced plugin $('#element').myPlugin(); // Initialize $('#element').myPlugin('show'); // Call method $('#element').myPlugin({color: 'red'}); // Initialize with options

🆚 jQuery vs Vanilla JavaScript

Common Operations Comparison

Operation Vanilla JavaScript jQuery
Document Ready document.addEventListener('DOMContentLoaded', function() {}) $(function() {})
Select by ID document.getElementById('id') $('#id')
Select by Class document.getElementsByClassName('class') $('.class')
Select by Tag document.getElementsByTagName('div') $('div')
Query Selector document.querySelector('.class') $('.class')
Query Selector All document.querySelectorAll('.class') $('.class')
Add Event Listener element.addEventListener('click', handler) $('#id').on('click', handler)
Get/Set Text element.textContent
element.textContent = 'text'
$('#id').text()
$('#id').text('text')
Get/Set HTML element.innerHTML
element.innerHTML = 'html'
$('#id').html()
$('#id').html('html')
Get/Set Value input.value
input.value = 'value'
$('input').val()
$('input').val('value')
Add Class element.classList.add('class') $('#id').addClass('class')
Remove Class element.classList.remove('class') $('#id').removeClass('class')
Toggle Class element.classList.toggle('class') $('#id').toggleClass('class')
Set CSS element.style.color = 'red' $('#id').css('color', 'red')
Get Attribute element.getAttribute('src') $('#id').attr('src')
Set Attribute element.setAttribute('src', 'img.jpg') $('#id').attr('src', 'img.jpg')
Create Element document.createElement('div') $('<div>')
Append Child parent.appendChild(child) $('#parent').append(child)
Remove Element element.remove() $('#id').remove()
AJAX Request fetch('/api').then(r => r.json()) $.getJSON('/api', function(data) {})

When to Use jQuery

Use jQuery when:

  • You need to support older browsers (IE8-10)
  • You want simpler, more readable code
  • You need lots of DOM manipulation
  • You want built-in animations and effects
  • You're working with AJAX extensively
  • You want access to jQuery plugins
  • Your team is already using jQuery

Use Vanilla JS when:

  • You only need to support modern browsers
  • You want better performance (jQuery adds ~30KB)
  • You're building a small, simple application
  • You want to learn modern JavaScript
  • You're using a modern framework (React, Vue, Angular)
  • You need the latest browser features

💻 jQuery Playground

Live jQuery Editor

Output will appear here...

Try These Examples

📋 jQuery Cheat Sheet

Quick Reference

Core

  • $(selector) - Select elements
  • $(function(){}) - Document ready
  • $.each() - Iterate array/object
  • $.extend() - Merge objects
  • $.ajax() - AJAX request

Selectors

  • $('#id') - By ID
  • $('.class') - By class
  • $('tag') - By tag name
  • $('[attr]') - By attribute
  • $(':first') - First element

Traversing

  • .parent() - Get parent
  • .children() - Get children
  • .find() - Find descendants
  • .siblings() - Get siblings
  • .next() - Next sibling
  • .prev() - Previous sibling

Manipulation

  • .html() - Get/set HTML
  • .text() - Get/set text
  • .val() - Get/set value
  • .append() - Append content
  • .prepend() - Prepend content

Events

  • .on() - Attach event
  • .off() - Remove event
  • .click() - Click event
  • .hover() - Hover event
  • .submit() - Form submit

Effects

  • .show() - Show element
  • .hide() - Hide element
  • .toggle() - Toggle visibility
  • .fadeIn() - Fade in
  • .fadeOut() - Fade out
  • .slideDown() - Slide down

CSS

  • .css() - Get/set CSS
  • .addClass() - Add class
  • .removeClass() - Remove class
  • .toggleClass() - Toggle class
  • .hasClass() - Check class

Attributes

  • .attr() - Get/set attribute
  • .removeAttr() - Remove attribute
  • .data() - Get/set data
  • .removeData() - Remove data
  • .prop() - Get/set property

AJAX Shortcuts

  • $.get() - GET request
  • $.post() - POST request
  • $.getJSON() - GET JSON
  • $.getScript() - Load script
  • .load() - Load HTML

Best Practices

  • Always use $(document).ready()
  • Cache jQuery objects: var $el = $('#element');
  • Use event delegation for dynamic elements
  • Chain methods when possible
  • Use .on() and .off() instead of shorthand methods
  • Minify jQuery for production
  • Use CDN for better caching
  • Keep selectors as specific as possible