HCDD 411
1 / 16

jQuery

Md Touhidul Islam

While jQuery is not recommended for new projects, you'll encounter it in:
  • Legacy codebases at internships and jobs
  • Enterprise applications built 5-15 years ago

Quick Review: HTML + CSS

How structure and style work together

Remember: HTML defines the structure (what elements exist), and CSS defines the style (how they look). They're separate but work together. Try editing both below!
HTML
📄 index.html
Ln 1, Col 1 HTML
CSS
🎨 styles.css
Ln 1, Col 1 CSS
🎨 Live Preview:
💡 Try this: Change the .card background color, or change the button text in the HTML. Hit "Update Preview" to see your changes!

The Problem: Vanilla JS is Verbose

Changing content dynamically requires a lot of code

The Challenge: What if we want to change content after the page loads? We need JavaScript to manipulate the DOM. But vanilla JS can be... wordy.

Example: Change text, style, and add an element

TRY IT: Vanilla JS
📄 script.js
Ln 1, Col 1 JavaScript (Vanilla)
💻 Console Output:
🎨 Live Preview:

Original Heading

  • Item One
  • Item Two
  • Item Three
⚠️ Notice the pain points:
  • document.getElementById() and document.getElementsByClassName() — long method names
  • Need a for loop just to change multiple elements
  • Creating elements requires multiple lines: createElement, set properties, then appendChild

What is jQuery?

A fast, small JavaScript library that simplifies web development

The Core Idea:
jQuery provides simple, short commands to do things that would otherwise take many lines of JavaScript. Its motto: "Write less, do more."

What jQuery Makes Easier

🎯 Finding Elements

Select any element on the page using CSS-style selectors — by ID, class, tag, or complex combinations.

🔧 Changing Content

Read or modify text, HTML, attributes, and form values with simple one-line commands.

🎨 Styling Elements

Change CSS properties, add/remove classes, and toggle styles dynamically.

⚡ Handling Events

Respond to clicks, hovers, key presses, and other user interactions easily.

✨ Animations

Show, hide, fade, and slide elements with built-in animation methods.

🌐 AJAX Requests

Fetch data from servers without reloading the page — simplified HTTP requests.

The Problem jQuery Solved:
In the mid-2000s, browsers (IE, Firefox, Chrome, Safari) all implemented JavaScript differently. Code that worked in one browser would break in another. jQuery provided a single, consistent way to write code that worked everywhere.

The Rise and Fall of jQuery

2006

jQuery released - revolutionary for its time. Made cross-browser development possible.

2006-2015

Dominated web development. Used on 70%+ of all websites.

2015+

React, Vue, Angular emerge. Modern browsers become consistent.

Today

Still on ~77% of sites (legacy), but rarely chosen for new projects.

Why jQuery Became Less Relevant:
  • Modern browsers are consistent - No need for cross-browser fixes
  • Vanilla JS improved - querySelector, fetch, classList
  • Frameworks emerged - React, Vue, Angular handle DOM better

Including jQuery

Option 1: CDN (Recommended)

HTML: Using CDN
📄 index.html
HTML + JavaScript jQuery 3.7.1
💡 The $ Symbol
$ is just an alias for jQuery. When you see $("...") in code, that's jQuery!
Compare: The same task with jQuery
// All that vanilla JS... becomes this:
$("#main-heading").text("New Title!");
$(".item").css({"color": "blue", "font-weight": "bold"});
$("#container").append("<p style='background:#10B981;color:white;padding:10px'>Added!</p>");

3 lines instead of 15+! That's the power of jQuery.

jQuery Selectors

The foundation of jQuery - selecting elements

Basic Syntax: $("selector")

Selection Type jQuery Vanilla JS
By ID $("#myId") document.getElementById("myId")
By Class $(".myClass") document.querySelectorAll(".myClass")
By Tag $("div") document.querySelectorAll("div")
What the code below does:
  • $("#demo-box") — Selects the element with ID "demo-box" and adds a red border
  • $(".demo-item") — Selects ALL elements with class "demo-item" and changes their text to blue
  • .length — Returns how many elements were found (useful for debugging)
TRY IT: Selectors
📄 script.js
Ln 1, Col 1 JavaScript + jQuery
Tab Indent Ctrl+Enter Run
💻 Console Output:
🎨 Live Preview:

Demo Box

  • Item 1
  • Item 2
  • Item 3

DOM Manipulation - Content

Reading and changing element content

Method Description Vanilla JS
.html() Get/set HTML content (parses tags) innerHTML
.text() Get/set text only (ignores tags) textContent
.val() Get/set form input values value
What the code below does:
  • .html("<strong>...</strong>") — Replaces content and renders the HTML tags
  • .text("<em>...</em>") — Replaces content but shows tags as plain text
  • .val() — Gets the current input value; .val("new") sets it
TRY IT: Content Methods
📄 script.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview:
Original content here
Text demo area

DOM Manipulation - Styling

Changing CSS and toggling classes

Method Description
.css("property", "value") Set a single CSS property
.css({prop1: val1, prop2: val2}) Set multiple CSS properties at once
.addClass() / .removeClass() Add or remove a CSS class
.toggleClass() Add class if missing, remove if present
What the code below does:
  • .css({...}) — Applies multiple inline styles to the element
  • .addClass("highlight") — Adds a predefined CSS class
  • .toggleClass("active") — Run multiple times to see it toggle on/off
TRY IT: Styling
📄 script.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview:
Style Box
Class Demo
Toggle Box (run multiple times)

DOM Manipulation - Elements

Adding and removing elements from the page

Method Description
.append(content) Add inside element, at the end
.prepend(content) Add inside element, at the start
.after(content) Add outside, immediately after
.remove() Delete the element entirely
What the code below does:
  • .append() — Adds a new list item at the end of the list
  • .prepend() — Adds a new list item at the beginning
  • $("<div>") — Creates a brand new element that you can then insert
TRY IT: Adding Elements
📄 script.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview:
  • Original Item 1
  • Original Item 2

🎯 Practice: Selectors & Styling

Try it yourself! Complete the tasks below.

Your Tasks:
  1. Select the element with ID greeting and change its text to "Hello, jQuery!"
  2. Select ALL elements with class box and give them a blue background (#3B82F6)
  3. Select the element with ID special and add the class highlight
💡 Hints:
  • Use $("#id") to select by ID
  • Use $(".class") to select by class
  • Use .text("...") to change text
  • Use .css("property", "value") to change styles
  • Use .addClass("className") to add a class
YOUR CODE
📄 practice.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview:

Welcome to the page

Box 1
Box 2
Box 3
I'm special!

🎯 Practice: Content & Elements

Manipulate content and add new elements!

Your Tasks:
  1. Get the value from the input with ID username and log it to the console
  2. Change the HTML inside #message to: <strong>Updated!</strong>
  3. Add a new list item <li>Item 4</li> to the end of #todo-list
💡 Hints:
  • Use .val() to get input values
  • Use .html("...") to set HTML content (renders tags)
  • Use .append("...") to add content at the end
  • Use console.log(...) to output to the console
YOUR CODE
📄 practice.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview:
Original message here
To-Do List:
  • Item 1
  • Item 2
  • Item 3

Event Handling

Responding to user interactions

Method Description
.on("click", fn) Attach any event handler (preferred method)
.click(fn) Shorthand for click events
.hover(fnIn, fnOut) Handle mouseenter and mouseleave
$(this) Reference to the element that triggered the event
What the code below does:
  • .click(function() {...}) — Runs the function when element is clicked
  • $(this) — Inside the handler, refers to the clicked element
  • .hover() — First function runs on mouse enter, second on mouse leave
TRY IT: Events (run, then interact)
📄 script.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview (interact after running):
Hover Over Me
  • Click to select - Item 1
  • Click to select - Item 2

DOM Traversal

Navigating between related elements

Method Description
.parent() Select the direct parent element
.children() Select all direct children
.siblings() Select all sibling elements
.find("selector") Search within descendants
.first() / .last() / .eq(n) Select specific element from a set
What the code below does:
  • .first() / .last() — Selects first or last element from matched set
  • .eq(1) — Selects element at index 1 (zero-based, so second item)
  • .find("li") — Searches for all <li> elements inside the container
TRY IT: Traversal
📄 script.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview:

Animations

Built-in effects for showing, hiding, and transitioning

Method Description
.show() / .hide() / .toggle() Display or hide elements instantly or with duration
.fadeIn() / .fadeOut() / .fadeToggle() Animate opacity
.slideDown() / .slideUp() / .slideToggle() Animate height
.animate({props}, duration) Custom animations with any CSS properties
What the code below does:
  • Each button triggers a different animation on the box
  • Duration can be "slow", "fast", or milliseconds like 500
  • .animate() lets you animate any numeric CSS property
TRY IT: Animations (run, then click buttons)
📄 script.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview:
Animate Me!

jQuery vs Modern JavaScript

Side-by-side comparison — everything jQuery does, vanilla JS can do too

Task jQuery Modern Vanilla JS
Select element $("#id") document.querySelector("#id")
Select all $(".class") document.querySelectorAll(".class")
Add class $(el).addClass("x") el.classList.add("x")
Set CSS $(el).css("color", "red") el.style.color = "red"
Set HTML $(el).html("...") el.innerHTML = "..."
Click event $(el).click(fn) el.addEventListener("click", fn)
AJAX request $.get(url, callback) fetch(url).then(r => r.json())
💡 Key Takeaway:
jQuery was essential when browsers were inconsistent. Today, vanilla JS has caught up. Use jQuery for legacy projects, but prefer modern JS or frameworks like React for new work.

Document Ready

Ensuring the DOM is loaded before your code runs

⚠️ Why this matters:
If your JavaScript runs before the HTML is fully loaded, jQuery won't find the elements you're trying to select. Always wrap your code in a document ready handler.
Syntax Description
$(document).ready(function() {...}) Full syntax — runs when DOM is ready
$(function() {...}) Shorthand — same thing, less typing
REFERENCE: Document Ready Pattern
📄 script.js
Reference Only JavaScript + jQuery
💡 Modern alternative:
In vanilla JS, use document.addEventListener("DOMContentLoaded", function() {...}) — or simply place your <script> tag at the end of <body>.

🎯 Final Practice: Events & Interactions

Make the page interactive!

Your Tasks:
  1. When #color-btn is clicked, change #color-box background to green (#10B981)
  2. When #fade-btn is clicked, fade out #fade-box
  3. When any .list-item is clicked, add the class selected to it
💡 Hints:
  • Use .click(function() { ... }) to handle clicks
  • Use .fadeOut() to fade an element
  • Use $(this) inside an event handler to refer to the clicked element
YOUR CODE (run first, then interact)
📄 practice.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview (interact after running!):
Color
Fade

Click items to select:

  • Apple
  • Banana
  • Cherry

🎯 Final Practice: Build a Mini Feature

Combine everything you've learned!

Build a simple "Add to Cart" feature:
  1. When #add-btn is clicked, get the text from #product-name
  2. Create a new list item with that product name
  3. Append it to #cart-list
  4. Bonus: Clear the input after adding
💡 Hints:
  • Use .val() to get input text
  • Use string concatenation: "<li>" + variable + "</li>"
  • Use .append() to add to the list
  • Use .val("") to clear an input
YOUR CODE
📄 practice.js
Ln 1, Col 1 JavaScript + jQuery
💻 Console Output:
🎨 Live Preview (run code, then try adding products!):

🛒 Shopping Cart

Cart Items:
  • Keyboard
  • Mouse