0% found this document useful (0 votes)
28 views89 pages

Unit 2

Uploaded by

Aaliya Tabassum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views89 pages

Unit 2

Uploaded by

Aaliya Tabassum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

📘 Subtopic 1: JavaScript Basics – Scripts, Document &

Window Object, Variables & Operators

Introduction

JavaScript (often abbreviated as JS) is the programming language that powers the web. It
was first introduced in 1995 by Netscape as a way to make web pages interactive. Initially
called “LiveScript,” it was later renamed JavaScript. Today, it is standardized as ECMAScript
(ES), with new versions being released regularly (ES6/ES2015 being a major milestone).

JavaScript is now everywhere:

 Client-Side: Runs inside the web browser to handle UI interactions, validate forms,
manipulate the DOM, and create animations.

 Server-Side: Thanks to environments like Node.js, JavaScript can also run outside the
browser to handle backend logic, databases, and APIs.

 Cross-Platform: It’s used in mobile app development (React Native), desktop


applications (Electron), and even game development.

In the browser, JavaScript works hand-in-hand with HTML and CSS:

 HTML gives the structure.

 CSS adds the style.

 JavaScript introduces the behavior.

Example: When you click a button and see a pop-up message, it’s JavaScript in action.

Internal and External Scripts

JavaScript code can be included in two main ways:

Internal Scripts

These are written directly inside the <script> tag within an HTML file. They are useful for
small snippets.

✅ Example:

<!DOCTYPE html>

<html>

<head>
<title>Internal Script</title>

</head>

<body>

<h1>Welcome</h1>

<script>

alert("This is an internal script running!");

</script>

</body>

</html>

External Scripts

Here the code is stored in a separate .js file and linked with the src attribute. This approach is
cleaner and reusable.

✅ Example:

<!-- index.html -->

<script src="app.js"></script>

<!-- app.js -->

alert("This is an external script!");

defer and async Attributes

 defer: Delays script execution until after HTML is fully parsed.

 async: Executes script asynchronously (good for independent scripts like ads or
analytics).

✅ Example:

<script src="script.js" defer></script>

<script src="tracker.js" async></script>

Pros & Cons


Aspect Internal Script External Script

Location Inside HTML Separate .js file

Reusability Limited Reusable

Performance OK for small code Better for larger apps (caching)

Best Use Quick testing Real projects

Document and Window Object

Window Object

Represents the browser window. It is the global object in the browser. Functions like alert(),
prompt(), confirm(), and timers (setTimeout(), setInterval()) belong to the window object.

✅ Example:

window.alert("This is an alert!");

console.log(window.innerWidth); // width of the browser window

Document Object

Represents the DOM (Document Object Model) — the HTML page structure. With it, you
can access and modify page elements dynamically.

Common methods:

 document.getElementById("id")

 document.getElementsByClassName("class")

 document.querySelector("selector")

 document.querySelectorAll("selector")

✅ Example:

<h1 id="title">Hello</h1>

<script>

document.getElementById("title").innerHTML = "Changed with JavaScript!";

</script>

DOM Tree (Text Diagram)

[ Window ]
├── Document

│ ├── HTML

│ │ ├── Head

│ │ └── Body

│ │ ├── h1

│ │ └── p

└── Browser properties (history, location, navigator, etc.)

More Examples

// Change styles

document.getElementById("title").style.color = "red";

// Add new element

let p = document.createElement("p");

p.innerText = "This is a new paragraph!";

document.body.appendChild(p);

Variables

Variables are containers for storing data. JavaScript has three main keywords for declaring
them:

1. var – function-scoped, can be redeclared.

2. let – block-scoped, introduced in ES6, cannot be redeclared.

3. const – block-scoped, constant value, must be initialized.

✅ Example:

var name = "Alice"; // function-scoped

let age = 22; // block-scoped

const pi = 3.1416; // constant

Scope & Hoisting

 var variables are hoisted and initialized as undefined.


 let and const are hoisted but kept in a temporal dead zone (TDZ) until initialized.

✅ Example:

console.log(a); // undefined

var a = 10;

console.log(b); // ReferenceError

let b = 20;

Comparison Table

Feature var let const

Scope Function Block Block

Redeclaration Allowed ❌ Not allowed ❌ Not allowed

Reassignment Allowed Allowed ❌ Not allowed

Hoisting Yes Yes (TDZ) Yes (TDZ)

Operators

JavaScript includes many operators:

Arithmetic Operators

+, -, *, /, %, ++, --

let a = 10, b = 3;

console.log(a + b); // 13

console.log(a % b); // 1

Comparison Operators

== vs ===

console.log(5 == "5"); // true (type conversion)

console.log(5 === "5"); // false (strict equality)

Logical Operators

let x = true, y = false;


console.log(x && y); // false

console.log(x || y); // true

Assignment Operators

let num = 10;

num += 5; // 15

num *= 2; // 30

Ternary Operator

let age = 18;

let result = (age >= 18) ? "Adult" : "Minor";

console.log(result); // Adult

Template Literals vs Concatenation

let name = "Alice";

console.log("Hello " + name); // old way

console.log(`Hello ${name}`); // modern way

Bitwise Example

console.log(5 & 1); // 1 (AND)

console.log(5 | 1); // 5 (OR)

console.log(5 ^ 1); // 4 (XOR)

Cheatsheet (Expanded)

Category Operator / Keyword Example

Arithmetic +, -, *, /, % 10 % 3 → 1

Comparison ==, ===, != 5 === "5" → false

Logical &&, ||, ! (x>0 && y>0)

Assignment =, +=, -= x += 2;

String +, Template literals `Hello ${name}`

Variables var, let, const let x = 20;


Category Operator / Keyword Example

DOM document.getElementById document.getElementById("id")

Global window.alert window.alert("Hi!")

Mini Project – Greeting App (Extended)

✅ Example:

<!DOCTYPE html>

<html>

<head>

<title>Greeting App</title>

</head>

<body>

<h2>Enter Your Name:</h2>

<input type="text" id="nameInput">

<button onclick="greet()">Greet Me</button>

<p id="output"></p>

<script>

function greet() {

let userName = document.getElementById("nameInput").value;

let hour = new Date().getHours();

let greeting;

if (hour < 12) {

greeting = "Good Morning";

} else if (hour < 18) {

greeting = "Good Afternoon";

} else {
greeting = "Good Evening";

document.getElementById("output").innerHTML =

`${greeting}, ${userName}! Welcome to JavaScript.`;

</script>

</body>

</html>

This demonstrates:

 Internal script

 Document object (getElementById)

 Variables (let, const)

 Operators (if-else, +, template literals)

Summary

 JavaScript is the language of the web, standardized as ECMAScript.

 It can be written internally or as external scripts, with defer and async attributes for
performance.

 The window object represents the browser; the document object represents the
DOM.

 Variables are declared with var, let, or const (block/function scope, hoisting
differences).

 Operators include arithmetic, comparison, logical, assignment, and ternary, with


additional support for template literals and bitwise operations.

 With these basics, students can already build dynamic apps like a Greeting App with
time-based messages.
📘 Subtopic 2: Data Types & Core Operations

Introduction

In JavaScript, data types define the kind of values that can be stored and manipulated in
programs. Unlike strongly typed languages such as Java or C++, JavaScript is dynamically
typed. This means that a variable can hold a value of any type, and its type can change at
runtime.

For example:

let x = 10; // number

x = "Hello"; // string (same variable, different type)

This flexibility makes JavaScript powerful but also requires developers to understand how
data types, conversions, and operations behave. Along with data types, JavaScript provides
built-in core operations like Math functions and string manipulation, which form the
foundation for building larger applications.

Data Types in JavaScript

Primitive Data Types

These are simple, immutable data types.

1. Number
Represents integers and floating-point numbers.

2. let age = 25;

3. let price = 19.99;

4. String
Represents text, enclosed in quotes (" ", ' ', or backticks `).

5. let name = "Alice";

6. let greeting = `Hello, ${name}`; // template literal

7. Boolean
Represents logical values: true or false.

8. let isStudent = true;


9. let isLoggedIn = false;

10. Undefined
A variable declared but not assigned a value.

11. let x;

12. console.log(x); // undefined

13. Null
Represents the intentional absence of value.

14. let empty = null;

15. Symbol (ES6)


Unique identifiers.

16. let id = Symbol("123");

17. let anotherId = Symbol("123");

18. console.log(id === anotherId); // false

19. BigInt (ES11)


Represents very large integers beyond Number.MAX_SAFE_INTEGER.

20. let big = 1234567890123456789012345678901234567890n;

Reference Data Types

These are complex data types stored by reference.

1. Objects
Collection of key-value pairs.

2. let person = { name: "Alice", age: 25 };

3. Arrays
Ordered lists of values.

4. let fruits = ["apple", "banana", "cherry"];

5. Functions
First-class objects; they can be assigned to variables.

6. function add(a, b) { return a + b; }

Checking Type with typeof


console.log(typeof "hello"); // string

console.log(typeof 42); // number

console.log(typeof true); // boolean

console.log(typeof {}); // object

console.log(typeof []); // object (arrays are objects)

console.log(typeof null); // object (quirk in JS)

Type Conversion

JavaScript performs conversions automatically (implicit coercion) or explicitly when you use
functions.

Implicit (Type Coercion)

console.log("5" + 2); // "52" (number converted to string)

console.log("5" - 2); // 3 (string converted to number)

console.log(1 + true); // 2 (true → 1)

Explicit Conversion

let num = Number("123"); // 123

let str = String(123); // "123"

let bool = Boolean(0); // false

let parsed = parseInt("45"); // 45

let float = parseFloat("3.14"); // 3.14

Comparison Table

Conversion Implicit Explicit

String → Number "5" - 2 → 3 Number("5") → 5

Number → String "5" + 2 → "52" String(5) → "5"

Boolean → Number true + 1 → 2 Number(true) → 1


Math Operations

JavaScript has the built-in Math object for mathematical operations.

Common Math Methods

console.log(Math.round(4.7)); // 5

console.log(Math.floor(4.9)); // 4

console.log(Math.ceil(4.1)); // 5

console.log(Math.pow(2, 3)); // 8

console.log(Math.sqrt(16)); // 4

console.log(Math.random()); // random number between 0 and 1

Generate Random Number in Range

function getRandom(min, max) {

return Math.floor(Math.random() * (max - min + 1)) + min;

console.log(getRandom(1, 10)); // random number 1–10

📋 Math Cheatsheet

Method Description Example

Math.round() Round to nearest integer Math.round(4.7) → 5

Math.floor() Round down Math.floor(4.9) → 4

Math.ceil() Round up Math.ceil(4.1) → 5

Math.pow() Power Math.pow(2,3) → 8


Method Description Example

Math.sqrt() Square root Math.sqrt(9) → 3

Math.random() Random (0–1) 0.53

String Manipulation

Strings are one of the most frequently used data types.

Properties & Methods

let str = "Hello World";

console.log(str.length); // 11

console.log(str.toUpperCase()); // "HELLO WORLD"

console.log(str.toLowerCase()); // "hello world"

console.log(str.substring(0, 5)); // "Hello"

console.log(str.slice(-5)); // "World"

console.log(str.replace("World", "JS")); // "Hello JS"

console.log(str.split(" ")); // ["Hello", "World"]

Template Literals

let name = "Alice";

console.log("Hello " + name); // old way

console.log(`Hello ${name}!`); // modern way

Escape Characters

let text = "Line1\nLine2\tTabbed";

console.log(text);

📋 String Cheatsheet

Method Description Example

.length String length "Hi".length → 2

.toUpperCase() Uppercase "hi".toUpperCase() → "HI"


Method Description Example

.toLowerCase() Lowercase "HI".toLowerCase() → "hi"

.substring(start,end) Extract part "hello".substring(0,2) → "he"

.slice(start) Extract with negatives "hello".slice(-2) → "lo"

.replace(a,b) Replace text "hi".replace("hi","bye")

.split(delim) Split string "a,b".split(",") → ["a","b"]

Diagrams (Text-based)

Data Types Classification

Data Types

├── Primitive

│ ├── Number

│ ├── String

│ ├── Boolean

│ ├── Null

│ ├── Undefined

│ ├── Symbol

│ └── BigInt

└── Reference

├── Object

├── Array

└── Function

Conversion Flow

"123" --Number()--> 123

123 --String()--> "123"

0 --Boolean()--> false

"false" --Boolean()--> true


Mini Project – Math & String Utility App

Idea

Create a small app where the user enters a number and a string. The app will show:

 Square, cube, and random number (using Math).

 String in uppercase, lowercase, and reversed.

Code

<!DOCTYPE html>

<html>

<head><title>Math & String Utility</title></head>

<body>

<h2>Utility App</h2>

<input type="number" id="numInput" placeholder="Enter a number">

<input type="text" id="strInput" placeholder="Enter a string">

<button onclick="process()">Process</button>

<h3>Results:</h3>

<p id="output"></p>

<script>

function process() {

let num = Number(document.getElementById("numInput").value);

let str = document.getElementById("strInput").value;

let square = Math.pow(num, 2);

let cube = Math.pow(num, 3);

let randomNum = Math.floor(Math.random() * 100);


let upper = str.toUpperCase();

let lower = str.toLowerCase();

let reversed = str.split("").reverse().join("");

document.getElementById("output").innerHTML =

`Number: ${num}<br>

Square: ${square}, Cube: ${cube}, Random: ${randomNum}<br>

Upper: ${upper}, Lower: ${lower}, Reversed: ${reversed}`;

</script>

</body>

</html>

Summary

 JavaScript supports primitive (string, number, boolean, null, undefined, symbol,


bigint) and reference (objects, arrays, functions) data types.

 Type conversion can be implicit (coercion) or explicit using functions like Number(),
String().

 The Math object provides useful methods like round(), floor(), ceil(), random(),
pow().

 Strings are powerful with methods like .toUpperCase(), .slice(), .replace(), and
template literals.
 With these operations, we can create practical utilities like the Math & String Utility
App.

📘 Subtopic 3: Conditional Statements & Functions

Introduction

Every program needs to make decisions and perform reusable tasks. In real life, we make
decisions constantly:

 If it rains, we carry an umbrella.

 If traffic light is red, we stop; otherwise, we go.

Similarly, in programming, conditional statements help us make choices based on conditions.

Functions, on the other hand, allow us to bundle code into reusable blocks. Instead of
rewriting the same logic multiple times, we can call a function whenever needed. Together,
conditionals and functions are the building blocks of any application.

Conditional Statements

1. The if Statement

Executes code only if a condition is true.

✅ Example:

let age = 20;

if (age >= 18) {

console.log("You are eligible to vote.");

}
2. The if...else Statement

Executes one block if true, another if false.

✅ Example:

let num = 7;

if (num % 2 === 0) {

console.log("Even number");

} else {

console.log("Odd number");

3. The if...else if...else Ladder

Checks multiple conditions.

✅ Example:

let marks = 75;

if (marks >= 90) {

console.log("Grade: A+");

} else if (marks >= 75) {

console.log("Grade: A");

} else if (marks >= 50) {

console.log("Grade: B");

} else {

console.log("Fail");

4. The switch Statement


Used for cleaner multiple-choice logic.

✅ Example:

let day = 3;

switch(day) {

case 1: console.log("Monday"); break;

case 2: console.log("Tuesday"); break;

case 3: console.log("Wednesday"); break;

default: console.log("Invalid day");

5. Nested Conditionals

Conditions inside other conditions.

✅ Example:

let age = 25;

let hasID = true;

if (age >= 18) {

if (hasID) {

console.log("Entry allowed");

} else {

console.log("No ID, no entry");

} else {

console.log("Underage");

📊 Comparison Table: if-else vs switch


Feature if-else switch

Use case Range-based conditions Fixed values

Syntax More verbose Cleaner for multiple cases

Flexibility Very flexible Limited to equality checks

Functions in JavaScript

1. Function Declaration

function greet(name) {

return `Hello, ${name}`;

console.log(greet("Alice"));

2. Function Expression

Assigned to a variable.

const square = function(num) {

return num * num;

};

console.log(square(5)); // 25

3. Arrow Functions (ES6)

Shorter syntax.

const add = (a, b) => a + b;

console.log(add(2, 3)); // 5

4. Default Parameters

function multiply(a, b = 2) {
return a * b;

console.log(multiply(5)); // 10

5. Scope of Functions

Variables inside functions are local.

function test() {

let x = 10; // local

console.log(x);

test();

console.log(x); // Error

Advanced Function Concepts

Callback Functions

Functions passed as arguments.

function processUserInput(callback) {

let name = "Alice";

callback(name);

processUserInput(function(n) {

console.log("Hello " + n);

});

First-Class Functions

In JavaScript, functions are treated like variables.

function sayHi() {
return "Hi!";

let greet = sayHi;

console.log(greet()); // "Hi!"

Anonymous Functions

Functions without names.

setTimeout(function() {

console.log("Executed after 2 seconds");

}, 2000);

Recursion

A function that calls itself.

function factorial(n) {

if (n === 0) return 1;

return n * factorial(n - 1);

console.log(factorial(5)); // 120

Diagrams (Text-based)

Conditional Flow

[Condition]

├── True → Execute Block A

└── False → Execute Block B

Function Call Stack

main()

├── call greet()


│ └── returns value

└── continues execution

Cheatsheet Tables

Conditionals Cheatsheet

Statement Syntax Example

if if (cond) { } if (x>0) { }

if-else if (cond) {} else {} if (x>0){...} else {...}

else-if if...else if...else if(x>0){...} else if(x<0){...}

switch switch(expr){case val:...} switch(day){case 1:"Mon"}

Functions Cheatsheet

Type Syntax Example

Declaration function fn(){} function add(a,b){}

Expression const fn = function(){} const sq = function(x){}

Arrow const fn = () => {} const add = (a,b)=>a+b

Default param function fn(a=1){} function sum(x=10){}

Mini Project – Student Grading System

Idea

 Input: Student’s marks.

 Logic: Use conditionals to assign grade.

 Functions: Encapsulate grading logic.

Code

<!DOCTYPE html>

<html>

<head><title>Grading System</title></head>

<body>
<h2>Enter Marks:</h2>

<input type="number" id="marksInput">

<button onclick="showGrade()">Check Grade</button>

<p id="result"></p>

<script>

function calculateGrade(marks) {

if (marks >= 90) return "A+";

else if (marks >= 75) return "A";

else if (marks >= 50) return "B";

else return "Fail";

function showGrade() {

let marks = document.getElementById("marksInput").value;

let grade = calculateGrade(marks);

document.getElementById("result").innerHTML = "Your Grade: " + grade;

</script>

</body>

</html>

Summary

 Conditional statements (if, if-else, switch) allow decisions based on conditions.

 switch is ideal for multiple fixed choices, while if-else works for ranges.

 Functions allow reusable blocks of code: declarations, expressions, arrow functions,


recursion, and callbacks.

 JavaScript treats functions as first-class citizens, meaning they can be assigned,


passed, and returned.
 With conditionals + functions, we can build useful programs like a Student Grading
System.

📘 Subtopic 4: Java Libraries & jQuery Basics

Introduction to Java Libraries

In programming, a library is a collection of pre-written code that provides useful functions


and utilities so developers don’t have to “reinvent the wheel.” In JavaScript, libraries are
extremely popular because they solve common problems such as DOM manipulation,
animations, data handling, date formatting, and more.

Some well-known JavaScript libraries are:

 jQuery → DOM manipulation, events, AJAX, effects.

 Lodash → Utility functions for arrays, objects, strings.

 Moment.js → Date and time formatting.

 Chart.js → Interactive charts and graphs.

👉 Library vs Framework

 A library gives you tools, and you choose how to use them (e.g., jQuery).

 A framework defines the overall structure and flow of your program (e.g., Angular,
React).

📊 Comparison Table

Feature Library Framework

Control Developer calls library functions Framework calls developer’s code

Example jQuery, Lodash Angular, React, Vue

Flexibility High Less (structured flow)

Introduction to jQuery
Before modern JavaScript added features like querySelector, fetch(), and better event
handling, developers struggled with browser compatibility issues. jQuery, created in 2006,
became the most popular JavaScript library because it:

 Simplified DOM selection and manipulation.

 Handled cross-browser differences.

 Made AJAX requests easier.

 Provided built-in animations and effects.

Although many of its features have now been adopted by vanilla JavaScript, jQuery is still
widely used, especially in legacy projects.

Adding jQuery to a Page

You can include jQuery using a CDN (Content Delivery Network):

<!DOCTYPE html>

<html>

<head>

<title>jQuery Example</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>

<h1>Hello jQuery!</h1>

<script>

$(document).ready(function() {

alert("jQuery is working!");

});

</script>

</body>

</html>

jQuery Selectors

Selectors are the backbone of jQuery. They are used to “find” elements in the DOM.
 By ID → $("#id")

 By Class → $(".class")

 By Tag → $("tag")

 Universal → "*"

✅ Examples:

$("#title").text("Changed using jQuery!");

$(".highlight").css("color", "red");

$("p").hide();

DOM Manipulation with jQuery

jQuery makes it simple to read and modify content:

Get/Set Content

$("#myDiv").text("Hello World"); // sets text

let val = $("#myInput").val(); // gets input value

Add/Remove Elements

$("#list").append("<li>New Item</li>");

$("#list").prepend("<li>First Item</li>");

$("#list").remove();

CSS Manipulation

$("#box").css("background-color", "blue");

$("#box").addClass("active");

$("#box").removeClass("hidden");

Events in jQuery

jQuery simplifies event handling.

Mouse Events

$("#btn").click(function() {

alert("Button clicked!");
});

$("#box").mouseenter(function() {

$(this).css("background", "yellow");

});

Keyboard Events

$("#input").keypress(function() {

console.log("Key pressed!");

});

Form Events

$("#form").submit(function(event) {

event.preventDefault();

alert("Form submitted!");

});

Document Ready

$(document).ready(function() {

console.log("DOM fully loaded");

});

Effects in jQuery

jQuery provides simple animations:

$("#box").hide();

$("#box").show();

$("#box").toggle();

$("#box").fadeIn();

$("#box").fadeOut();

$("#box").slideUp();

$("#box").slideDown();
Cheatsheets

Selectors Cheatsheet

Selector Example Meaning

#id $("#title") Selects element with ID “title”

.class $(".item") Selects all elements with class “item”

tag $("p") Selects all <p> elements

* $("*") Selects all elements

Events & Effects Cheatsheet

Method Description Example

.click() On click event $("#btn").click(...)

.mouseenter() Mouse hover $("#box").mouseenter(...)

.keypress() Key press event $("#input").keypress(...)

.submit() On form submit $("#form").submit(...)

.hide() Hides element $("#box").hide()

.fadeIn() Fade in effect $("#box").fadeIn()

.slideDown() Slide down effect $("#box").slideDown()

Diagrams (Text-based)

Library vs Framework
Library

→ Collection of tools

→ Developer decides flow

Framework

→ Defines structure

→ Inverts control ("Don’t call us, we call you")

jQuery Workflow

HTML Page → DOM

jQuery Selectors → Find Elements

Events → Add interactivity

Effects → Animations

Mini Project – Interactive To-Do List with jQuery

Idea

 User can type a task and add it to a list.

 Click a task to mark it as completed.

 Button to remove tasks.

Code

<!DOCTYPE html>

<html>

<head>

<title>To-Do List</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

.done { text-decoration: line-through; color: gray; }


</style>

</head>

<body>

<h2>My To-Do List</h2>

<input type="text" id="taskInput" placeholder="Enter a task">

<button id="addBtn">Add Task</button>

<ul id="taskList"></ul>

<script>

$(document).ready(function() {

$("#addBtn").click(function() {

let task = $("#taskInput").val();

if (task !== "") {

$("#taskList").append("<li>" + task + " <button class='remove'>X</button></li>");

$("#taskInput").val("");

});

$("#taskList").on("click", "li", function() {

$(this).toggleClass("done");

});

$("#taskList").on("click", ".remove", function() {

$(this).parent().remove();

});

});

</script>

</body>
</html>

Summary

 JavaScript libraries provide reusable tools for common tasks.

 jQuery simplified DOM selection, event handling, AJAX, and animations.

 jQuery selectors are powerful for targeting elements.

 DOM manipulation is easy with .text(), .html(), .append(), .css().

 Events and effects make pages interactive.

 With just a few lines of jQuery, we can build dynamic apps like a To-Do List.

📘 Subtopic 5: DOM & Page Elements

Introduction to the DOM

The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of a web page as a tree of objects, where each element (like <p>,
<div>, <h1>) becomes a node in the tree.

When a browser loads a web page:

1. It reads the HTML file.

2. Constructs the DOM tree.

3. JavaScript can then access, modify, or delete parts of this tree.

👉 Example:

<!DOCTYPE html>

<html>

<head><title>DOM Example</title></head>
<body>

<h1 id="title">Hello World</h1>

</body>

</html>

In the DOM, this page is represented as:

Document

└── html

├── head

│ └── title

└── body

└── h1 (#title)

Thus, the DOM allows JavaScript to dynamically interact with the page.

DOM Tree Structure

The DOM is structured hierarchically like a family tree:

 Root: document (the whole page).

 Element Nodes: HTML tags (<p>, <div>, <img>).

 Text Nodes: The text inside tags.

 Attribute Nodes: Properties like id, class, src.

📐 Diagram (Text-based)

Document

└── html

├── head

│ └── title → "My Page"

└── body

├── h1 → "Heading"

├── p → "Paragraph"
└── img (src="pic.jpg")

Accessing Page Elements

JavaScript provides methods to access nodes in the DOM.

getElementById()

Finds an element by its ID.

let title = document.getElementById("title");

title.style.color = "blue";

getElementsByClassName()

Finds multiple elements by class.

let items = document.getElementsByClassName("item");

items[0].style.fontWeight = "bold";

getElementsByTagName()

Finds all elements with a given tag.

let paras = document.getElementsByTagName("p");

console.log(paras.length);

querySelector()

Finds the first element matching a CSS selector.

let firstPara = document.querySelector("p");

querySelectorAll()

Finds all elements matching a CSS selector.

let allParas = document.querySelectorAll("p");

allParas.forEach(p => p.style.color = "green");

Modifying Page Elements

Changing Content

 .innerHTML → modifies HTML inside element.

 .textContent → modifies text only.


document.getElementById("title").innerHTML = "<i>Welcome</i>";

document.getElementById("title").textContent = "Just Text";

Working with Attributes

let img = document.getElementById("photo");

img.setAttribute("src", "newpic.jpg");

let altText = img.getAttribute("alt");

Modifying CSS Styles

let box = document.getElementById("box");

box.style.backgroundColor = "yellow";

box.style.border = "2px solid red";

Creating & Removing Elements

JavaScript can create new elements dynamically.

Creating & Appending

let newPara = document.createElement("p");

newPara.textContent = "This is a new paragraph!";

document.body.appendChild(newPara);

Removing Elements

let para = document.getElementById("removeMe");

para.remove();

Traversing the DOM

DOM traversal allows moving around the tree.

Parent & Child Nodes

let child = document.getElementById("item1");

console.log(child.parentNode); // parent element

console.log(child.childNodes); // all child nodes


First & Last Child

let list = document.getElementById("list");

console.log(list.firstChild);

console.log(list.lastChild);

Sibling Elements

let item = document.getElementById("item2");

console.log(item.nextElementSibling); // next item

console.log(item.previousElementSibling); // previous item

📐 Traversal Diagram

<ul id="list">

├── li (#item1)

├── li (#item2) ← current

└── li (#item3)

From #item2:

 .parentNode → <ul>

 .previousElementSibling → #item1

 .nextElementSibling → #item3

Cheatsheets

Common DOM Methods

Method Description Example

getElementById() Get element by ID document.getElementById("id")

Get elements by
getElementsByClassName() document.getElementsByClassName("cls")
class

querySelector() Get first match document.querySelector(".cls")

querySelectorAll() Get all matches document.querySelectorAll("p")

DOM Traversal Shortcuts


Property Description Example

.parentNode Get parent node.parentNode

.childNodes Get children node.childNodes

.firstChild Get first child list.firstChild

.lastChild Get last child list.lastChild

.nextElementSibling Next element item.nextElementSibling

.previousElementSibling Previous element item.previousElementSibling

Mini Project – Dynamic List Manager

Idea

Create a list where the user can:

 Add new items.

 Click to remove items.

 Demonstrates DOM creation, modification, and removal.

Code

<!DOCTYPE html>

<html>

<head>

<title>Dynamic List Manager</title>

</head>

<body>

<h2>My List</h2>

<input type="text" id="itemInput" placeholder="Enter item">


<button onclick="addItem()">Add</button>

<ul id="list"></ul>

<script>

function addItem() {

let input = document.getElementById("itemInput");

let text = input.value;

if (text !== "") {

let li = document.createElement("li");

li.textContent = text;

li.onclick = function() {

this.remove();

};

document.getElementById("list").appendChild(li);

input.value = "";

</script>

</body>

</html>

Summary

 The DOM is a tree structure representing an HTML page.

 Elements can be accessed using methods like getElementById, querySelector, etc.

 Content and attributes can be modified with .innerHTML, .textContent, .setAttribute.


 New elements can be created with createElement and removed with .remove().

 Traversal allows moving between parent, child, and sibling nodes.

 With these tools, we can build interactive apps like a Dynamic List Manager.

📘 Subtopic 6: jQuery Selectors & Filters

Introduction to Selectors

In jQuery, selectors are the foundation of everything. They allow developers to find and
target elements in the DOM (Document Object Model) so that we can manipulate them.

In vanilla JavaScript, targeting an element can be verbose:

document.getElementById("title").style.color = "blue";

With jQuery, the same action is much simpler:

$("#title").css("color", "blue");

This brevity makes jQuery powerful and beginner-friendly. Selectors can be combined with
filters to refine results even further, allowing precise control over which elements to target.

Basic Selectors

By ID

Selects element with the given ID.

$("#title").text("Changed via jQuery!");

By Class

Selects all elements with the given class.

$(".highlight").css("background", "yellow");

By Tag

Selects all elements with a specific tag.

$("p").css("font-size", "18px");
Universal Selector

Selects all elements.

$("*").css("margin", "5px");

Hierarchy Selectors

These help select elements based on parent-child or sibling relationships.

Descendant Selector ("div p")

Selects all <p> inside <div>.

$("div p").css("color", "green");

Child Selector ("div > p")

Selects direct children <p> of <div>.

$("div > p").css("font-weight", "bold");

Adjacent Sibling ("h1 + p")

Selects the immediately next sibling.

$("h1 + p").css("color", "red");

General Sibling ("h1 ~ p")

Selects all siblings after <h1>.

$("h1 ~ p").css("font-style", "italic");

📐 Hierarchy Example

<div>

<h1>Main Heading</h1>

<p>First paragraph</p> ← Adjacent sibling

<p>Second paragraph</p> ← General sibling

</div>

Attribute Selectors

jQuery selectors can also filter by attributes.


Basic Attribute ([attr])

Selects elements with a given attribute.

$("img[alt]").css("border", "2px solid red");

Exact Match ([attr=value])

$("input[type='text']").val("Hello");

Not Equal ([attr!=value])

$("a[target!='_blank']").css("color", "orange");

Prefix Match ([attr^=value])

$("input[name^='user']").css("background", "#f0f0f0");

Suffix Match ([attr$=value])

$("img[src$='.png']").css("border-radius", "5px");

Substring Match ([attr*=value])

$("a[href*='google']").css("color", "blue");

Filter Selectors

Filters refine results further after selecting.

First & Last

$("p:first").css("color", "blue");

$("p:last").css("color", "red");

Even & Odd

$("tr:even").css("background", "#eee"); // even rows

$("tr:odd").css("background", "#ccc"); // odd rows

Specific Index (:eq, :gt, :lt)

$("li:eq(2)").css("color", "purple"); // 3rd element

$("li:gt(2)").css("color", "orange"); // greater than index 2

$("li:lt(2)").css("color", "green"); // less than index 2

Negation (:not)

$("p:not(.special)").css("font-style", "italic");
Form Filters

$(":text").val("Default text");

$(":password").css("border", "2px solid red");

$(":checked").parent().css("color", "green");

$(":disabled").css("background", "#ddd");

Cheatsheets
Common Selectors

Selector Example Meaning

#id $("#title") Selects element with ID “title”

.class $(".item") Selects elements with class “item”

tag $("p") Selects all <p> elements

* $("*") Selects all elements

Hierarchy Selectors

Selector Example Meaning

ancestor descendant div p All <p> inside <div>

parent > child div > p Direct child <p> inside <div>

prev + next h1 + p Immediate sibling

prev ~ siblings h1 ~ p All next siblings

Filters

Filter Example Meaning

:first $("p:first") First <p> element


Filter Example Meaning

:last $("p:last") Last <p> element

:even $("tr:even") Even-indexed rows

:odd $("tr:odd") Odd-indexed rows

:eq(n) $("li:eq(2)") 3rd element (index starts 0)

:gt(n) $("li:gt(2)") Greater than index 2

:lt(n) $("li:lt(2)") Less than index 2

:not(sel) $("p:not(.special)") Excludes .special

:checked $(":checked") Checked checkbox/radio

:disabled $(":disabled") Disabled inputs

Diagrams (Text-based)

Selection Flow

DOM → jQuery Selector → Filter (refine) → Apply Action

Example

$("table tr:odd").css("background", "gray");

DOM

└── table

├── tr (0) even

├── tr (1) odd ← styled

├── tr (2) even

└── tr (3) odd ← styled


Mini Project – Dynamic Table Highlighter

Idea

Create a table where rows are dynamically styled using jQuery filters:

 Highlight odd/even rows with alternating colors.

 First and last row styled differently.

 Selected row (on click) gets highlighted.

Code

<!DOCTYPE html>

<html>

<head>

<title>Dynamic Table Highlighter</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

table { border-collapse: collapse; width: 50%; }

td, th { border: 1px solid black; padding: 8px; text-align: center; }

.highlight { background-color: yellow; }

</style>

</head>

<body>

<h2>Student Marks</h2>

<table>

<tr><th>Name</th><th>Marks</th></tr>

<tr><td>Alice</td><td>90</td></tr>

<tr><td>Bob</td><td>75</td></tr>

<tr><td>Charlie</td><td>60</td></tr>

<tr><td>Diana</td><td>85</td></tr>

</table>
<script>

$(document).ready(function() {

$("tr:even").css("background", "#f2f2f2");

$("tr:odd").css("background", "#ddd");

$("tr:first").css("font-weight", "bold");

$("tr:last").css("color", "red");

$("tr").click(function() {

$("tr").removeClass("highlight");

$(this).addClass("highlight");

});

});

</script>

</body>

</html>

Summary

 jQuery selectors make it easy to find elements by ID, class, tag, or hierarchy.

 Attribute selectors help filter elements by properties like src, type, etc.

 Filters (:first, :last, :eq, :even, etc.) allow finer selection.

 Form filters are useful for handling inputs like :text, :password, :checked.

 Combining selectors and filters gives precise control over DOM manipulation.

 Practical applications like the Dynamic Table Highlighter show their power in real
projects.

📘 Subtopic 7: jQuery Events (Mouse, Document, Form, Keyboard)


Introduction to Events

An event is an action or occurrence in the browser that JavaScript can respond to. Examples
include:

 A user clicking a button.

 Pressing a key on the keyboard.

 Submitting a form.

 Resizing the browser window.

In vanilla JavaScript, events are handled with addEventListener. For example:

document.getElementById("btn").addEventListener("click", function() {

alert("Button clicked!");

});

With jQuery, this becomes shorter and easier:

$("#btn").click(function() {

alert("Button clicked!");

});

This simplicity is one of the main reasons developers adopted jQuery widely.

Mouse Events

jQuery supports several mouse interactions:

.click()

Triggered when an element is clicked.

$("#btn").click(function() {

alert("Button was clicked!");

});

.dblclick()

Triggered when an element is double-clicked.

$("#box").dblclick(function() {

$(this).css("background", "orange");
});

.mouseenter() and .mouseleave()

Triggered when the mouse enters or leaves an element.

$("#photo").mouseenter(function() {

$(this).css("border", "3px solid blue");

}).mouseleave(function() {

$(this).css("border", "none");

});

.hover()

Shortcut for handling both enter and leave.

$("#menu").hover(

function() { $(this).css("color", "green"); },

function() { $(this).css("color", "black"); }

);

Keyboard Events

Keyboard events detect key activity in input fields or across the document.

.keypress()

Fires when a key is pressed.

$("#input").keypress(function() {

console.log("Key pressed!");

});

.keydown() and .keyup()

 .keydown() → fires when a key is pressed down.

 .keyup() → fires when a key is released.

$("#input").keydown(function(e) {

console.log("Key down: " + e.key);

});
$("#input").keyup(function(e) {

console.log("Key up: " + e.key);

});

Example – Live Character Counter

$("#textBox").keyup(function() {

let length = $(this).val().length;

$("#count").text("Characters: " + length);

});

Form Events

Forms are interactive, and jQuery makes them easier to manage.

.submit()

Triggered when a form is submitted.

$("#myForm").submit(function(e) {

e.preventDefault();

alert("Form submitted!");

});

.change()

Triggered when the value of an input changes.

$("#dropdown").change(function() {

alert("Selected: " + $(this).val());

});

.focus() and .blur()

 .focus() → when an input gains focus.

 .blur() → when an input loses focus.

$("#username").focus(function() {

$(this).css("background", "#e0f7fa");

}).blur(function() {
$(this).css("background", "white");

});

Document & Window Events

$(document).ready()

Ensures the DOM is fully loaded before running scripts.

$(document).ready(function() {

console.log("DOM ready!");

});

$(window).resize()

Triggered when the browser window is resized.

$(window).resize(function() {

console.log("Window size changed!");

});

$(window).scroll()

Triggered when the user scrolls.

$(window).scroll(function() {

console.log("Scrolled!");

});

Event Object

Every event handler in jQuery receives an event object. This gives more details about the
action.

Example: event.target

$("button").click(function(event) {

alert("Clicked on: " + event.target.id);

});

Prevent Default Action


Stops default behavior (e.g., form submit, link click).

$("a").click(function(event) {

event.preventDefault();

alert("Link blocked!");

});

Stop Propagation

Prevents the event from bubbling up the DOM.

$("#child").click(function(event) {

event.stopPropagation();

alert("Child clicked");

});

Cheatsheets

Mouse Events

Event Description Example

.click() Single click $("#btn").click(...)

.dblclick() Double click $("#box").dblclick(...)

.mouseenter() Mouse enters element $("#div").mouseenter(...)

.mouseleave() Mouse leaves element $("#div").mouseleave(...)

.hover() Enter + leave shortcut $("#menu").hover(...)

Keyboard Events

Event Description Example

.keypress() Key pressed $("#input").keypress(...)

.keydown() Key pressed down $("#input").keydown(...)

.keyup() Key released $("#input").keyup(...)

Form Events
Event Description Example

.submit() On form submit $("#form").submit(...)

.change() Value changed $("#dropdown").change(...)

.focus() Input focused $("#username").focus(...)

.blur() Input loses focus $("#username").blur(...)

Diagrams (Text-based)

Event Lifecycle

User Action → Event Triggered → Event Object Created → Event Handler Executes

Event Bubbling vs Capturing

Event starts at innermost element

↑ Bubbling (default, bottom → up)

↓ Capturing (top → down, rarely used)

Mini Project – Interactive Login Form

Idea

 Highlight input fields on focus.

 Remove highlight on blur.

 Validate non-empty fields on submit.

 Allow pressing Enter to submit form.

Code

<!DOCTYPE html>

<html>

<head>
<title>Interactive Login</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

.highlight { border: 2px solid blue; }

</style>

</head>

<body>

<h2>Login Form</h2>

<form id="loginForm">

<input type="text" id="username" placeholder="Username"><br><br>

<input type="password" id="password" placeholder="Password"><br><br>

<button type="submit" id="loginBtn">Login</button>

</form>

<p id="msg"></p>

<script>

$(document).ready(function() {

// Focus and blur

$("input").focus(function() {

$(this).addClass("highlight");

}).blur(function() {

$(this).removeClass("highlight");

});

// Submit

$("#loginForm").submit(function(e) {

e.preventDefault();

let user = $("#username").val();


let pass = $("#password").val();

if(user === "" || pass === "") {

$("#msg").text("Both fields required!").css("color", "red");

} else {

$("#msg").text("Login successful!").css("color", "green");

});

// Keyboard (Enter key)

$("#password").keyup(function(e) {

if(e.key === "Enter") {

$("#loginBtn").click();

});

});

</script>

</body>

</html>

Summary

 Events are user actions like clicks, typing, or submitting forms.

 jQuery simplifies event handling with shorter syntax.

 Mouse, keyboard, form, and document events are commonly used.

 Event objects provide extra information and control (preventDefault,


stopPropagation).

 With events, we can build interactive applications like an Interactive Login Form.
📘 Subtopic 8: jQuery Event Concepts

Introduction to Event Concepts

Events are a cornerstone of interactive web development. They allow pages to respond
when users click buttons, type text, scroll, or submit forms.

In jQuery, event handling is made much simpler compared to vanilla JavaScript. However, as
web applications grew in complexity, developers faced challenges:

 How to handle events on elements created dynamically (after the page loads).

 How to manage multiple events on the same element.

 How to remove event listeners when no longer needed.

jQuery introduced powerful concepts like delegated event handling, event chaining, and
event namespaces to solve these issues.

Direct Event Binding

The simplest way to handle an event in jQuery is by binding it directly to an element.

$("#btn").click(function() {

alert("Button clicked!");

});

This works fine for static elements already present in the DOM. However, if elements are
added dynamically, direct binding won’t apply to them.

Delegated Event Handling with .on()

Delegation solves the dynamic problem. Instead of binding events directly, you attach the
handler to a parent element that exists at page load, and jQuery automatically applies it to
matching child elements.

// Delegation

$("#list").on("click", "li", function() {

$(this).toggleClass("done");

});
Even if new <li> items are added later, they will still respond to the click because the event is
delegated through #list.

👉 Why use delegation?

 Works for dynamically added content.

 Reduces memory usage (fewer handlers).

 Cleaner code for lists, tables, and large apps.

Event Chaining

jQuery allows chaining multiple event-related actions together:

$("#box").mouseenter(function() {

$(this).css("background", "yellow");

}).mouseleave(function() {

$(this).css("background", "white");

}).click(function() {

$(this).fadeOut();

});

Here, #box changes color on hover and fades out on click—all chained neatly.

Multiple Events Binding

You can attach multiple events in a single .on() call:

$("#btn").on({

click: function() { alert("Clicked!"); },

mouseenter: function() { $(this).css("color", "green"); },

mouseleave: function() { $(this).css("color", "black"); }

});

This makes code cleaner when dealing with several interactions on one element.

Event Namespaces
Namespaces help organize events and remove them selectively.

// Bind namespaced event

$("#btn").on("click.myNamespace", function() {

alert("Namespaced click event!");

});

// Remove only namespaced events

$("#btn").off("click.myNamespace");

This is useful in large applications where different modules might attach similar events.

Event Propagation

Events travel through the DOM in two phases:

1. Capturing Phase → from root down to target.

2. Bubbling Phase → from target back up to root (default in jQuery).

Example – Bubbling

$("#parent").click(function() {

alert("Parent clicked");

});

$("#child").click(function(event) {

alert("Child clicked");

});

Clicking the child will also trigger the parent unless stopped.

Stop Bubbling

$("#child").click(function(event) {

event.stopPropagation();

alert("Child only!");

});

Prevent Default
$("a").click(function(event) {

event.preventDefault(); // stops navigation

alert("Link blocked");

});

Removing Events

You can unbind events using .off().

$("#btn").on("click", function() {

alert("Click event bound");

});

// Remove all click handlers

$("#btn").off("click");

With namespaces, you can remove specific handlers without affecting others.

Cheatsheet

Concept Method Example

Direct binding .click(), .keyup() $("#btn").click(...)

Delegation .on(event, selector, handler) $("#list").on("click","li",...)

Multiple events .on({}) $("#btn").on({click:..., mouseenter:...})

Namespaces .on("click.ns") $("#btn").on("click.myNS",...)

Remove events .off() $("#btn").off("click")

Stop bubbling event.stopPropagation() Inside handler

Prevent default event.preventDefault() Block link submit

Diagrams (Text-based)

Event Flow (Bubbling)


<html>

<body>

<div id="parent">

<button id="child">Click Me</button>

</div>

</body>

</html>

Click #child

child handler → parent handler → body → html

Delegated Event Handling

Parent (#list) listens

Child (li) event captured by parent

Handler applied to correct child

Mini Project – Dynamic To-Do List with Event Delegation

Idea

 Add tasks dynamically.

 Click a task to mark as completed.

 Remove tasks using delegation.

Code

<!DOCTYPE html>

<html>

<head>

<title>Delegated To-Do List</title>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

.done { text-decoration: line-through; color: gray; }

</style>

</head>

<body>

<h2>My To-Do List</h2>

<input type="text" id="taskInput" placeholder="Enter task">

<button id="addBtn">Add Task</button>

<ul id="taskList"></ul>

<script>

$(document).ready(function() {

// Add new tasks

$("#addBtn").click(function() {

let task = $("#taskInput").val();

if(task !== "") {

$("#taskList").append("<li>" + task + " <button class='remove'>X</button></li>");

$("#taskInput").val("");

});

// Delegated event for marking done

$("#taskList").on("click", "li", function() {

$(this).toggleClass("done");

});

// Delegated event for remove button


$("#taskList").on("click", ".remove", function(e) {

e.stopPropagation(); // prevent li click

$(this).parent().remove();

});

});

</script>

</body>

</html>

Summary

 jQuery offers multiple ways of handling events.

 Direct binding is simple but fails for dynamic elements.

 Delegation with .on() ensures even new elements get event handling.

 Chaining and multiple events make code more compact.

 Namespaces allow organizing and removing specific events.

 Propagation control (stop bubbling, prevent default) gives fine-grained control.

 With these, developers can build interactive apps like a Dynamic To-Do List that
supports new and removable items.

📘 Subtopic 9: jQuery Effects

Introduction to jQuery Effects

Interactivity is a core part of modern websites. Users expect elements to appear, disappear,
move, or animate smoothly instead of changing instantly.

Before CSS3 introduced transition and animation, developers relied heavily on jQuery Effects
to add dynamic interactions to web pages. jQuery simplified effects by providing ready-to-
use methods for showing, hiding, fading, sliding, and animating elements with minimal
code.

jQuery effects can:

 Improve user experience (smooth transitions).

 Highlight important changes on a page.

 Add engagement (sliding menus, fading messages).

Basic Show/Hide Effects

.show()

Displays hidden elements.

$("#box").show();

.hide()

Hides visible elements.

$("#box").hide();

.toggle()

Toggles between show() and hide().

$("#btn").click(function() {

$("#box").toggle();

});

👉 Useful for dropdowns, tooltips, and modals.

Fading Effects

Fading smoothly changes an element’s opacity.

.fadeIn()

Gradually displays a hidden element.

$("#btn").click(function() {

$("#photo").fadeIn("slow");

});
.fadeOut()

Gradually hides an element.

$("#btn").click(function() {

$("#photo").fadeOut(2000); // 2 seconds

});

.fadeToggle()

Alternates between fade in and fade out.

$("#btn").click(function() {

$("#photo").fadeToggle();

});

.fadeTo()

Fades element to a specific opacity.

$("#photo").fadeTo("slow", 0.3); // 30% visible

Sliding Effects

Slide effects move elements vertically.

.slideDown()

Reveals hidden content by sliding down.

$("#btn").click(function() {

$("#panel").slideDown("slow");

});

.slideUp()

Hides content by sliding up.

$("#btn").click(function() {

$("#panel").slideUp();

});

.slideToggle()
Toggles between sliding up and down.

$("#btn").click(function() {

$("#panel").slideToggle();

});

👉 Often used in accordion menus and FAQs.

Custom Animations with .animate()

The .animate() method lets you animate CSS properties.

$("#box").animate({

left: "200px",

opacity: 0.5,

height: "100px",

width: "100px"

}, 2000);

 First parameter = CSS properties to animate.

 Second parameter = duration (in ms or "slow" / "fast").

👉 Example: moving an object across the screen.

$("#btn").click(function() {

$("#car").animate({ left: "+=300px" }, 3000);

});

Chaining Effects

jQuery allows chaining multiple effects in sequence.

$("#box").fadeOut(1000)

.slideDown(1000)

.animate({ left: "200px" }, 1500);

👉 Cleaner code since no need to write multiple separate calls.


Stopping & Controlling Effects

Sometimes effects need to be stopped or delayed.

.stop()

Stops ongoing animations immediately.

$("#box").stop();

.delay()

Adds a delay before the next effect.

$("#box").fadeIn().delay(2000).fadeOut();

Example: Stop animation on hover

$("#box").hover(function() {

$(this).stop().css("background", "yellow");

});

Cheatsheet

Effect Description Example

.show() Displays hidden element $("#box").show();

.hide() Hides visible element $("#box").hide();

.toggle() Show/Hide toggle $("#box").toggle();

.fadeIn() Fade into view $("#img").fadeIn();

.fadeOut() Fade out of view $("#img").fadeOut();

.fadeToggle() Toggle fade in/out $("#img").fadeToggle();

.fadeTo() Fade to specific opacity $("#img").fadeTo("slow", 0.5);

.slideDown() Slide element down $("#panel").slideDown();

.slideUp() Slide element up $("#panel").slideUp();

.slideToggle() Toggle slide $("#panel").slideToggle();

.animate() Animate CSS properties $("#box").animate({left:"200px"});

.stop() Stop animations $("#box").stop();


Effect Description Example

.delay() Pause before next effect $("#box").delay(1000);

Diagrams (Text-based)

Effect Lifecycle

Trigger Event → Start Transition → Animation Frame Updates → Complete Callback

Queued Animations

$("#box")

.fadeOut(1000)

.slideDown(1000)

.animate({ left: "200px" }, 1500);

Execution order: fade → slide → animate.

Mini Project – Interactive FAQ Section

Idea

 A list of questions.

 Clicking a question reveals its answer with a slideDown effect.

 Clicking again hides the answer with slideUp.

 Extra polish: fade effect on hover.

Code

<!DOCTYPE html>

<html>

<head>

<title>FAQ Section</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

.question { cursor: pointer; font-weight: bold; margin: 10px 0; }

.answer { display: none; margin-left: 20px; }


</style>

</head>

<body>

<h2>FAQs</h2>

<div class="faq">

<div class="question">What is jQuery?</div>

<div class="answer">jQuery is a JavaScript library for DOM manipulation and


effects.</div>

<div class="question">What is .slideToggle()?</div>

<div class="answer">It toggles an element between sliding up and down.</div>

</div>

<script>

$(document).ready(function() {

$(".question").click(function() {

$(this).next(".answer").slideToggle();

}).hover(

function() { $(this).fadeTo(200, 0.7); },

function() { $(this).fadeTo(200, 1); }

);

});

</script>

</body>

</html>

Summary

 jQuery effects make pages interactive with minimal code.


 Basic effects: show/hide/toggle.

 Fading effects adjust opacity smoothly.

 Sliding effects create accordion-like behavior.

 .animate() allows custom animations with CSS properties.

 Chaining, .stop(), and .delay() give developers more control.

 Combined, they can create polished UI components like an Interactive FAQ Section.

📘 Subtopic 10: jQuery Form Validation

Introduction to Form Validation

Form validation is one of the most important parts of web development. It ensures that the
data submitted by users is complete, accurate, and in the correct format before it reaches
the server.

 Client-side validation (done in the browser with JavaScript/jQuery):

o Faster feedback to users.

o Prevents unnecessary server requests.

o Improves user experience.

 Server-side validation (done on the server after submission):

o More secure (client validation can be bypassed).

o Final authority to accept/reject data.

👉 Best practice: use both client-side and server-side validation. jQuery makes client-side
validation simpler and shorter compared to vanilla JavaScript.

Basic Input Validation

The most common check is ensuring fields are not left empty.
$("#form").submit(function(event) {

let username = $("#username").val();

if (username.trim() === "") {

alert("Username cannot be empty!");

event.preventDefault();

});

Here, .val() retrieves the input value, and .trim() removes leading/trailing spaces.

Validating Multiple Fields

Forms usually contain multiple fields like username, email, password. jQuery can validate all
of them before submission.

$("#loginForm").submit(function(event) {

let user = $("#username").val().trim();

let pass = $("#password").val().trim();

if (user === "" || pass === "") {

alert("Both fields are required!");

event.preventDefault();

});

👉 This ensures that no field is left empty.

Regular Expression (Regex) with jQuery

Regex (Regular Expressions) are patterns used to check formats like email or password
strength.

Email Validation

let email = $("#email").val();


let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

if (!pattern.test(email)) {

alert("Invalid email format!");

event.preventDefault();

Password Strength Validation

let password = $("#password").val();

let strongPass = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&]).{6,}$/;

if (!strongPass.test(password)) {

alert("Password must contain letters, numbers, and special characters.");

event.preventDefault();

Checkbox & Radio Validation

Sometimes users must check a box (e.g., Terms & Conditions) or choose a radio option (e.g.,
gender).

if (!$("#terms").is(":checked")) {

alert("You must agree to Terms & Conditions!");

event.preventDefault();

if (!$("input[name='gender']:checked").val()) {

alert("Please select a gender.");

event.preventDefault();

}
Select Dropdown Validation

Validating dropdowns ensures users select a valid option.

let country = $("#country").val();

if (country === "Select") {

alert("Please choose a country.");

event.preventDefault();

Error Messages & Styling

Instead of just alert(), we can show error messages beside fields and style them.

if ($("#username").val().trim() === "") {

$("#username").addClass("error");

$("#userError").text("Username is required");

event.preventDefault();

} else {

$("#username").removeClass("error");

$("#userError").text("");

👉 Using .addClass() and .removeClass() we can apply CSS like red borders for invalid inputs.

Form Submit Handling

The most important part is blocking form submission until all checks pass. This is done with
event.preventDefault().

$("#registerForm").submit(function(event) {

let valid = true;

if ($("#username").val().trim() === "") {


$("#userError").text("Username required");

valid = false;

if ($("#email").val().trim() === "") {

$("#emailError").text("Email required");

valid = false;

if (!valid) event.preventDefault();

});

Cheatsheet

Validation Task jQuery Method Example

Get input value .val() $("#username").val()

Check empty field .trim() if(val.trim()==="")

Checkbox selected .is(":checked") $("#terms").is(":checked")

Radio selected [name='x']:checked $("[name='gender']:checked").val()

Dropdown value .val() $("#country").val()

Add error class .addClass("error") $("#username").addClass("error")

Remove error class .removeClass("error") $("#username").removeClass("error")

Prevent submit event.preventDefault() Inside .submit() handler

Diagrams (Text-based)

Form Validation Flow

User Input


Validation Check

├── Pass → Allow Submission

└── Fail → Show Error → Block Submission

Validation with jQuery

Form Submit

jQuery Checks (empty fields, regex, checkboxes)

Errors?

├── Yes → preventDefault(), show error messages

└── No → submit form

Mini Project – Registration Form with Validation

Idea

A form with:

 Username

 Email

 Password + Confirm Password

 Gender (radio)

 Terms & Conditions (checkbox)

Validation rules:

 All fields required.

 Email must be valid format.


 Password must be strong + match confirmation.

 Gender must be selected.

 Terms must be accepted.

Code

<!DOCTYPE html>

<html>

<head>

<title>Registration Form</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

.error { border: 2px solid red; }

.error-msg { color: red; font-size: 12px; }

</style>

</head>

<body>

<h2>Register</h2>

<form id="registerForm">

Username: <input type="text" id="username"><span id="userError" class="error-


msg"></span><br><br>

Email: <input type="text" id="email"><span id="emailError"


class="error-msg"></span><br><br>

Password: <input type="password" id="password"><br><br>

Confirm Password: <input type="password" id="confirmPass"><span id="passError"


class="error-msg"></span><br><br>

Gender:

<input type="radio" name="gender" value="Male">Male

<input type="radio" name="gender" value="Female">Female<span id="genderError"


class="error-msg"></span><br><br>

<input type="checkbox" id="terms"> I agree to Terms<span id="termsError" class="error-


msg"></span><br><br>
<button type="submit">Register</button>

</form>

<p id="msg"></p>

<script>

$("#registerForm").submit(function(event) {

let valid = true;

// Username

if ($("#username").val().trim() === "") {

$("#userError").text("Required"); valid = false;

} else { $("#userError").text(""); }

// Email

let email = $("#email").val();

let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

if (!emailPattern.test(email)) {

$("#emailError").text("Invalid email"); valid = false;

} else { $("#emailError").text(""); }

// Password match

let pass = $("#password").val();

let confirm = $("#confirmPass").val();

if (pass === "" || pass !== confirm) {

$("#passError").text("Passwords must match"); valid = false;

} else { $("#passError").text(""); }

// Gender
if (!$("input[name='gender']:checked").val()) {

$("#genderError").text("Select gender"); valid = false;

} else { $("#genderError").text(""); }

// Terms

if (!$("#terms").is(":checked")) {

$("#termsError").text("Required"); valid = false;

} else { $("#termsError").text(""); }

if (!valid) event.preventDefault();

});

</script>

</body>

</html>

Summary

 Form validation ensures data quality and improves user experience.

 jQuery simplifies checks for empty fields, emails, passwords, checkboxes, and
dropdowns.

 Error messages can be shown inline with CSS styling for clarity.

 event.preventDefault() blocks submission until all checks pass.

 A complete example is the Registration Form with Validation, which ensures correct,
secure input before allowing submission.

📘 Subtopic 11: AJAX – GET and POST


Introduction to AJAX

AJAX stands for Asynchronous JavaScript and XML, but today JSON has largely replaced
XML as the preferred format. AJAX allows a webpage to send and receive data from the
server without reloading the entire page.

👉 Example of AJAX in action:

 Gmail loads new emails dynamically.

 Search engines show live suggestions as you type.

 Online shopping carts update without refreshing the page.

Before AJAX, updating data always required a full page reload, which was slow and
inefficient.

How AJAX Works

The workflow of AJAX can be broken down into 4 steps:

1. A user action triggers a request (e.g., clicking a button).

2. The browser (JavaScript/jQuery) sends an asynchronous request to the server.

3. The server processes the request and sends back a response.

4. JavaScript updates the webpage dynamically with the new data.

📐 AJAX Workflow (Text Diagram)

User Action → jQuery AJAX Request → Server Processes → Response Returned → Page
Updates

AJAX with jQuery

While vanilla JavaScript requires complex XMLHttpRequest objects, jQuery provides simpler
methods:

 .ajax() → Full control over request.

 .get() → Simplified GET request.

 .post() → Simplified POST request.

GET Request

The GET method is used when you want to retrieve data from the server.
Example – Fetch User List

$("#loadUsers").click(function() {

$.get("users.php", function(data) {

$("#userList").html(data);

});

});

 users.php → file on the server returning data.

 data → response from the server.

 $("#userList").html(data) → updates the webpage dynamically.

POST Request

The POST method is used to send data to the server, often when submitting forms.

Example – Submit Form

$("#submitBtn").click(function() {

$.post("submit.php",

name: $("#name").val(),

email: $("#email").val()

},

function(response) {

$("#msg").html(response);

);

});

 Data (name, email) is sent to submit.php.

 Server processes it and returns a response.


Handling Responses

AJAX requests can succeed or fail. jQuery provides .done(), .fail(), and .always() to handle
outcomes.

$.get("data.php")

.done(function(data) {

$("#result").html("Success: " + data);

})

.fail(function() {

$("#result").html("Error occurred");

})

.always(function() {

console.log("Request finished");

});

AJAX with JSON

JSON (JavaScript Object Notation) is lightweight and easy to parse. Most modern web APIs
return JSON data.

Example – Fetch JSON Data

$.get("students.json", function(data) {

$.each(data, function(index, student) {

$("#students").append("<li>" + student.name + " - " + student.grade + "</li>");

});

}, "json");

 "json" ensures the response is parsed automatically.

Example – Send JSON via POST

$.ajax({

url: "save.php",

type: "POST",

contentType: "application/json",
data: JSON.stringify({ name: "Alice", age: 21 }),

success: function(response) {

console.log("Saved:", response);

});

Error Handling

AJAX errors can occur due to network failure, wrong URL, or server error.

$.ajax({

url: "wrong.php",

type: "GET",

success: function(data) {

console.log("Data:", data);

},

error: function(xhr, status, error) {

console.log("Error: " + error);

});

👉 xhr gives details of the HTTP request.

Cheatsheet

Method Usage Example

.ajax() Full control over AJAX $.ajax({url:"x.php", type:"GET"})

.get() Retrieve data (GET) $.get("data.php", fn)

.post() Send data (POST) $.post("save.php", {...}, fn)

.done() Success handler $.get("x").done(fn)

.fail() Error handler $.get("x").fail(fn)


Method Usage Example

.always() Always runs $.get("x").always(fn)

GET vs POST

Feature GET POST

Purpose Retrieve data Send data

Data location URL query string Request body

Data limit Limited (URL length) Unlimited

Security Less secure (visible in URL) More secure

Diagrams (Text-based)

GET Request Flow

Browser → GET /data.php → Server responds with data → Page updates

POST Request Flow

Browser → POST /submit.php + form data → Server processes → Success/Failure message


returned

Mini Project – Live Search Application

Idea

 User types into a search box.

 AJAX GET request sends query to server.

 Matching results displayed instantly (like Google search suggestions).

Code

<!DOCTYPE html>
<html>

<head>

<title>Live Search</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

#results { border: 1px solid #ccc; max-width: 300px; }

#results div { padding: 5px; cursor: pointer; }

#results div:hover { background: #f0f0f0; }

</style>

</head>

<body>

<h2>Live Search</h2>

<input type="text" id="searchBox" placeholder="Search...">

<div id="results"></div>

<script>

$(document).ready(function() {

$("#searchBox").keyup(function() {

let query = $(this).val();

if (query.length > 0) {

$.get("search.php", { q: query }, function(data) {

$("#results").html(data);

});

} else {

$("#results").html("");

});

});
</script>

</body>

</html>

 search.php returns results based on the query.

 Results update without page reload.

Summary

 AJAX allows asynchronous communication with the server.

 GET is used to retrieve data, POST to send data.

 jQuery simplifies AJAX with .get(), .post(), and .ajax().

 .done(), .fail(), and .always() help manage responses.

 JSON is the most common data format in AJAX requests.

 Error handling ensures reliability.

 A Live Search Application demonstrates real-world AJAX usage.

📘 Subtopic 12: JSON – Accessing JSON Data

Introduction to JSON

JSON (JavaScript Object Notation) is one of the most widely used formats for storing and
exchanging data on the web. It is lightweight, text-based, and easy for both humans and
machines to read. JSON is built on two structures:

1. Objects → Collections of key-value pairs (similar to JavaScript objects).

2. Arrays → Ordered lists of values (similar to JavaScript arrays).

Why JSON is Important?

 Used by almost every modern API (e.g., weather apps, e-commerce, social media).

 Replaces XML for most applications due to its simplicity.

 Directly compatible with JavaScript because it is based on JavaScript syntax.


👉 Example use cases:

 Sending user data from a form to a server.

 Retrieving weather forecast from an API.

 Displaying product details dynamically.

JSON Structure

JSON follows a very simple syntax:

 Data is in key : value pairs.

 Keys are always strings.

 Values can be:

o String → "Hello World"

o Number → 25

o Boolean → true or false

o Array → [1,2,3]

o Object → { "key": "value" }

o Null → null

Example JSON

"student": {

"name": "Alice",

"age": 21,

"email": "[email protected]",

"isEnrolled": true,

"courses": ["HTML", "CSS", "JavaScript"]

}
Accessing JSON in JavaScript

Since JSON is based on JavaScript object syntax, you can access its values using dot notation
or bracket notation.

let data = {

student: {

name: "Alice",

age: 21,

email: "[email protected]",

isEnrolled: true,

courses: ["HTML", "CSS", "JavaScript"]

};

// Dot notation

console.log(data.student.name); // Alice

// Bracket notation

console.log(data["student"]["email"]); // [email protected]

// Access array

console.log(data.student.courses[0]); // HTML

Parsing JSON Strings

When data comes from an API or file, it is usually in string format. We use JSON.parse() to
convert it into an object.

let jsonString = '{"name":"Bob","age":22,"city":"Bangalore"}';

let obj = JSON.parse(jsonString);

console.log(obj.name); // Bob
console.log(obj.age); // 22

Stringifying Objects

To send data to a server, you may need to convert an object into a JSON string. Use
JSON.stringify().

let student = {

name: "Charlie",

age: 20,

course: "BCA"

};

let jsonData = JSON.stringify(student);

console.log(jsonData);

// Output: {"name":"Charlie","age":20,"course":"BCA"}

Iterating Over JSON Data

When you get JSON data from an API, you often need to loop through arrays or objects.

Iterating an Array

let students = [

{name: "Alice", grade: "A"},

{name: "Bob", grade: "B"},

{name: "Charlie", grade: "A"}

];

$.each(students, function(index, student) {

console.log(student.name + " - " + student.grade);

});

Iterating an Object
let user = { name: "David", age: 23, city: "Chennai" };

$.each(user, function(key, value) {

console.log(key + ": " + value);

});

Using JSON with AJAX

Most APIs return JSON data. jQuery makes it easy to fetch and process.

Fetch JSON with .getJSON()

$.getJSON("students.json", function(data) {

$.each(data, function(index, student) {

$("#list").append("<li>" + student.name + " - " + student.age + "</li>");

});

});

Send JSON Data with .ajax()

let student = { name: "Esha", age: 19 };

$.ajax({

url: "save.php",

type: "POST",

data: JSON.stringify(student),

contentType: "application/json",

success: function(response) {

console.log("Saved:", response);

});

Cheatsheet
Function Purpose Example

JSON.parse() Converts JSON string → JS object JSON.parse('{"name":"Alice"}')

JSON.stringify() Converts JS object → JSON string JSON.stringify(obj)

$.getJSON() Fetch JSON via GET $.getJSON("data.json", fn)

$.ajax() Full control for JSON requests $.ajax({url:"x", data: JSON.stringify(obj)})

Access object Dot / bracket obj.name or obj["name"]

Access array Index-based arr[0].value

Diagrams (Text-based)

JSON Hierarchy Example

"student": {

"name": "Alice",

"age": 21,

"courses": ["HTML", "CSS", "JS"]

AJAX + JSON Flow

Browser → AJAX Request → Server

← JSON Response ←

Parse JSON → Update Page Content

Mini Project – Student Records Viewer

Idea

 Store student data in a students.json file.

 Fetch JSON with AJAX.

 Display in a table dynamically using jQuery.


Sample JSON (students.json)

{"name":"Alice","age":21,"course":"BCA"},

{"name":"Bob","age":22,"course":"MCA"},

{"name":"Charlie","age":20,"course":"BSc"}

Code

<!DOCTYPE html>

<html>

<head>

<title>Student Records Viewer</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>

table { border-collapse: collapse; width: 60%; }

th, td { border: 1px solid black; padding: 8px; text-align: center; }

th { background: #f2f2f2; }

</style>

</head>

<body>

<h2>Student Records</h2>

<button id="loadBtn">Load Students</button>

<table>

<tr><th>Name</th><th>Age</th><th>Course</th></tr>

</table>

<script>

$("#loadBtn").click(function() {

$.getJSON("students.json", function(data) {
$.each(data, function(index, student) {

$("table").append("<tr><td>" + student.name + "</td><td>" +

student.age + "</td><td>" + student.course + "</td></tr>");

});

});

});

</script>

</body>

</html>

👉 When you click Load Students, the JSON data is fetched and added to the table
dynamically.

Summary

 JSON is a lightweight, text-based data format widely used in web apps.

 JSON data is structured as objects and arrays.

 Use JSON.parse() to convert strings → objects.

 Use JSON.stringify() to convert objects → strings.

 jQuery’s .getJSON() and .ajax() make working with JSON simple.

 Iterating JSON is easy using $.each().

 Real-world applications like the Student Records Viewer rely heavily on JSON for
data exchange.

You might also like