Tutorials

Jquery Tutorial

jquery
Share
jQuery Complete Tutorial for Beginners
πŸ“š Complete Beginner’s Guide

jQuery: From Zero to Hero

The friendliest jQuery tutorial on the internet. Learn to write powerful JavaScript in far fewer lines β€” no experience needed.

8 Chapters 40+ Code Examples Visual Infographics Free to Learn
Chapter 01

What is jQuery & Why Use It?

jQuery is a fast, small JavaScript library that makes it dramatically simpler to select HTML elements, handle events, create animations, and send server requests.

Think of JavaScript as a powerful but wordy language, and jQuery as a set of helpful shortcuts. Instead of writing five lines of plain JavaScript to do one thing, jQuery lets you do it in one line.

πŸ’‘
The jQuery Motto
“Write less, do more.” That’s the official slogan of jQuery β€” and it perfectly describes what the library is all about.
Vanilla JS vs jQuery β€” Side by Side

Here’s the same task done two ways β€” hiding an element with a red border when clicked:

❌ Plain JavaScript (verbose)
βœ… jQuery (concise)
What Can jQuery Do?
πŸ”

Find Elements

Grab any HTML element using CSS-style selectors β€” by ID, class, tag, and more.

✏️

Change Content

Update text, HTML, attributes, and CSS styles of any element on the page.

πŸ–±οΈ

Handle Events

React to clicks, keyboard input, mouse movements, form submissions, and more.

🎬

Animate

Fade elements in and out, slide panels, and build smooth custom animations.

🌐

Talk to Servers

Send and receive data from a web server without reloading the page (AJAX).

πŸ“¦

Cross-browser

Works the same in Chrome, Firefox, Safari and Edge β€” no compatibility headaches.

A Brief History of jQuery
2006
jQuery 1.0 is Born
John Resig releases jQuery at BarCamp NYC, solving the browser compatibility nightmare that every developer faced.
2009–2013
World Domination
jQuery becomes the most popular JavaScript library on Earth, used by over 65% of all websites.
2013
jQuery 2.0
Drops support for old IE browsers, making it smaller and faster for modern users.
2016–Now
jQuery 3.x (Latest)
Still actively maintained. Found on over 75% of all websites including WordPress, Wikipedia, and millions more.
🌍
Fun Fact
As of 2024, jQuery is still used by over 77% of the top 10 million websites. It’s the most widely deployed JavaScript library in history!

Chapter 02

Setting Up jQuery

Getting started with jQuery takes less than a minute. You have two main options: use a CDN link, or download the file yourself.

πŸ—ΊοΈ How jQuery Fits in a Web Page
🌐
Browser
requests the page
β†’
πŸ“„
HTML File
your page structure
β†’
πŸ“¦
jQuery
loaded via CDN
β†’
βš™οΈ
Your Script
uses jQuery’s $
β†’
✨
Magic!
interactive page
Method 1: CDN (Recommended for Beginners)

A CDN (Content Delivery Network) serves jQuery from fast servers around the world. Just copy this one line inside your HTML’s <head> tag β€” no downloads needed:

index.html
Method 2: Download & Host Yourself
  1. 1
    Go to jquery.com
    Visit jquery.com/download and click “Download the compressed, production jQuery 3.x.x”
  2. 2
    Save the file
    Put jquery.min.js in your project folder, e.g. in a js/ subfolder.
  3. 3
    Link it in your HTML
    Add <script src="js/jquery.min.js"></script> before your own script tag.
The Perfect Starter Template

Here’s a complete HTML file you can use as a starting point for every jQuery project:

starter-template.html
Understanding $(document).ready()

This is one of the most important concepts in jQuery. The $(document).ready() function ensures your code only runs after the entire HTML page has loaded:

// 3 ways to write the “ready” function β€” all identical:
 
// Way 1 β€” classic, easy to read
$(document).ready(function() {
// your code
});
 
// Way 2 β€” shorthand (most popular)
$(function() {
// your code
});
 
// Way 3 β€” modern arrow function
$(() => {
// your code
});
⚠️
Common Beginner Mistake
Always put your <script> tags at the bottom of <body>, or wrap your code in $(document).ready(). If you try to select an element before it exists in the HTML, jQuery can’t find it!

Chapter 03

Selectors β€” Finding Elements

Before you can do anything with an element, you need to find it. jQuery selectors work exactly like CSS selectors β€” so if you know CSS, you already know how to select elements!

The magic symbol in jQuery is the dollar sign $. You pass a selector string into it, and jQuery finds all matching elements for you.

The Basic Selector Map
$(‘p’)
Tag Selector
Selects ALL <p> elements on the page
$(‘#myId’)
ID Selector
Selects the ONE element with id=”myId”
$(‘.myClass’)
Class Selector
Selects ALL elements with class=”myClass”
$(‘*’)
Universal
Selects EVERY element (use sparingly!)
$(‘p.note’)
Combined
Selects <p> elements with class=”note”
$(‘div, p’)
Multiple
Selects all <div> AND all <p> elements
$(‘ul li’)
Descendant
Selects <li> elements inside <ul>
$(‘[href]’)
Attribute
Selects all elements that have an href attr
$(‘:first’)
First Filter
Selects the first matched element
Selectors in Action
selectors.js
Filtering Selectors β€” The Special Ones
SelectorWhat It MatchesExample
:firstThe very first matched element$('li:first')
:lastThe very last matched element$('li:last')
:evenElements with even index (0, 2, 4…)$('tr:even')
:oddElements with odd index (1, 3, 5…)$('tr:odd')
:eq(n)The element at index n$('li:eq(2)') β€” 3rd item
:not(sel)All elements NOT matching sel$('p:not(.intro)')
:emptyElements with no children or text$('td:empty')
:hiddenElements that are hidden$('div:hidden')
:visibleElements that are visible$('div:visible')
:contains(text)Elements that contain specific text$('p:contains("jQuery")')
βœ…
Pro Tip: Use IDs When Possible
Selecting by ID (#myId) is the fastest selector because IDs are unique. When speed matters, use IDs first, then classes, and avoid selecting by tag name alone on large pages.

Chapter 04

DOM Manipulation

The DOM (Document Object Model) is the live, in-memory version of your HTML. jQuery makes it incredibly easy to read and change any part of it.

Getting & Setting Content

The same methods work for both getting a value (no argument) and setting a value (with argument):

content.js
Adding & Removing Elements
MethodWhat It DoesPosition
append()Adds content inside the element, at the endEnd of children
prepend()Adds content inside the element, at the startStart of children
after()Adds content after the element (sibling)After element
before()Adds content before the element (sibling)Before element
remove()Removes the element and all its children from the DOMβ€”
empty()Removes all children, but keeps the element itselfβ€”
clone()Makes a copy of the elementβ€”
wrap()Wraps the element in a new HTML structureAround element
dom-manipulation.js
Working with CSS Classes

One of the most common tasks in jQuery is toggling CSS classes to show/hide things or change their appearance:

classes.js
Traversing the DOM β€” Moving Around

Once you’ve found an element, you can move to its relatives:

🌳 DOM Traversal β€” How to Navigate the Family Tree
<div id=”parent”> ← .parent()
|
<ul> ← YOU ARE HERE
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
<li> .children()
<li> .next() / .prev()
<li> .siblings()
.find(‘a’) searches ALL descendants  |  .closest(‘div’) goes UP the tree
traversal.js

Chapter 05

Events β€” Making Things Interactive

Events are how your page responds to the user. A click, a keypress, hovering over something β€” jQuery makes it effortless to listen for and react to any of these.

The Most Common Events
πŸ–±οΈ
.click()
Single mouse click
πŸ‘†
.dblclick()
Double click
🫲
.mouseenter()
Mouse moves over
πŸ’¨
.mouseleave()
Mouse moves away
⌨️
.keydown()
Key is pressed down
⬆️
.keyup()
Key is released
πŸ“
.submit()
Form is submitted
πŸ”„
.change()
Input value changes
🎯
.focus()
Element gets focus
πŸ’€
.blur()
Element loses focus
πŸ“œ
.scroll()
Element is scrolled
πŸ“
.resize()
Window is resized
Attaching Events with .on()

The modern and recommended way to attach events is with .on(). It’s flexible β€” you can attach multiple events at once:

events.js
Event Delegation β€” For Dynamic Elements

Event delegation is a powerful technique for elements that are added to the page after it loads. Instead of attaching events to individual elements, you attach them to a parent:

delegation.js
πŸ’‘
What is $(this)?
Inside an event handler, this refers to the specific element that triggered the event. Wrapping it in $(this) gives you the full jQuery power for that element. For example, if you click one of five buttons, $(this) refers to only the button you clicked.

Chapter 06

Effects & Animations

jQuery comes with built-in effects that make your pages feel alive β€” fading, sliding, and custom animations β€” all with just one line of code.

Show & Hide Effects
MethodWhat it doesSpeed Options
hide()Hides the element (shrinks it to nothing)‘slow’, ‘fast’, or ms number
show()Shows a hidden element‘slow’, ‘fast’, or ms number
toggle()Shows if hidden, hides if visible‘slow’, ‘fast’, or ms number
fadeIn()Fades element from invisible to visible‘slow’, ‘fast’, or ms number
fadeOut()Fades element out to invisible‘slow’, ‘fast’, or ms number
fadeToggle()Toggles fade in/out‘slow’, ‘fast’, or ms number
fadeTo()Fades to a specific opacity (0–1)speed + opacity required
slideDown()Reveals element with a downward slide‘slow’, ‘fast’, or ms number
slideUp()Hides element with an upward slide‘slow’, ‘fast’, or ms number
slideToggle()Toggles slide down/up‘slow’, ‘fast’, or ms number
effects.js
Custom Animations with .animate()

The .animate() method lets you animate any numeric CSS property β€” width, height, left, top, opacity, font-size, and more:

animate.js
βœ…
Method Chaining β€” jQuery’s Superpower
jQuery methods return the jQuery object, so you can chain multiple methods together on one line. $('#box').addClass('active').fadeIn(400).css('color','red') β€” all three things happen in sequence. It’s called “chaining” and it’s one of jQuery’s most elegant features.

Chapter 07

AJAX β€” Talking to Servers

AJAX stands for Asynchronous JavaScript And XML. It lets your page send requests to a server and receive data back β€” without ever reloading the page. Think of live search results, like-buttons, and infinite scroll.

πŸ”„ How AJAX Works β€” The Request/Response Cycle
1
πŸ‘€ User triggers an action
e.g. Types in a search box, clicks “Load More”, or submits a form.
2
βš™οΈ jQuery sends an HTTP request
jQuery uses $.ajax() or $.get() to send a request to a URL in the background.
3
🌐 Server processes the request
Your PHP, Node, Python (etc.) code runs and prepares a response β€” usually JSON or HTML.
4
πŸ“¦ Server sends back data
The server sends JSON, HTML, or plain text back as the response to the request.
5
✨ jQuery updates the page
Your callback function receives the data and updates the page β€” no refresh needed!
The Simple Way: $.get() and $.post()
ajax-simple.js
The Full $.ajax() Method

For complete control over your requests, use $.ajax():

ajax-full.js
Real-World Example: Live Search
live-search.js
βœ…
Load HTML Directly with .load()
jQuery’s .load() method is a shortcut that fetches HTML from a URL and injects it into an element: $('#content').load('about.html'); β€” perfect for loading page sections on demand.

Chapter 08

Quick Reference Cheat Sheet

Bookmark this page! Here’s everything you need at a glance β€” the most important jQuery methods organized by category.

πŸ” Selectors
$('#id')By ID
$('.class')By class
$('tag')By tag name
$('ul li')Descendant
$('a[href]')Has attribute
$(':first')First element
$(':hidden')Hidden elements
✏️ Content & Attributes
.text()Get/set text
.html()Get/set HTML
.val()Get/set input value
.attr('href')Get/set attribute
.removeAttr()Remove attribute
.css('color')Get/set style
.data('key')Get/set data-* attr
🌳 DOM Manipulation
.append()Add to end inside
.prepend()Add to start inside
.after()Add after element
.before()Add before element
.remove()Delete element
.empty()Clear children
.clone()Copy element
🎭 Classes
.addClass()Add CSS class
.removeClass()Remove CSS class
.toggleClass()Toggle CSS class
.hasClass()Check for class
πŸ–±οΈ Events
.on('click', fn)Attach event
.off('click')Remove event
.click(fn)Click shorthand
.hover(in, out)Hover in/out
.submit(fn)Form submit
.keyup(fn)Key released
e.preventDefault()Stop default
✨ Effects
.show() / .hide()Show/hide
.toggle()Toggle visibility
.fadeIn() / .fadeOut()Fade effects
.fadeToggle()Toggle fade
.slideDown() / .slideUp()Slide effects
.slideToggle()Toggle slide
.animate({})Custom animation
🌐 AJAX
$.get(url, fn)GET request
$.post(url, data, fn)POST request
$.ajax({})Full AJAX control
$.getJSON(url, fn)Fetch JSON
$('#el').load(url)Load HTML
🌳 Traversal
.parent()Direct parent
.children()Direct children
.find('sel')All descendants
.siblings()All siblings
.next() / .prev()Next/prev sibling
.closest('sel')Nearest ancestor
.each(fn)Loop elements
Key Brains